最近在看Aop的東西,正在瞭解這方面的東西。這篇主要是記錄一個最簡單的cglib編程示例。java
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency>
public class Dog { public void run() { System.out.println(" dog run .."); } }
public class CglibProxy implements MethodInterceptor { private Object proxy; public CglibProxy(Class clazz) { Enhancer enhancer = new Enhancer(); //設置須要建立的子類 enhancer.setSuperclass(clazz); //經過字節碼技術動態建立子類實例 enhancer.setCallback(this); this.proxy = enhancer.create(); } public Object getProxy() { return proxy; } @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("before"); Object result = methodProxy.invokeSuper(o, objects); System.out.println("after"); return result; } }
public class Client { public static void main(String[] args) { CglibProxy proxy = new CglibProxy(Dog.class); Dog dog = (Dog)proxy.getProxy(); dog.run(); } }
before編程
dog run ..maven
afteride
通常來講,JDK動態代理建立速度快,運行效率低;cglib建立速度慢,運行效率高。測試