探秘Spring AOP
一、Cglib 动态代理实现
- 1、代理类
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class DemoMethodInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("before in cglib");
Object res = null;
try {
res = methodProxy.invokeSuper(obj,args);
} catch (Exception e) {
System.out.println("ex "+ e);
throw e;
} finally {
System.out.println("after in cglib");
}
return res;
}
}
- 2、客户端调用方式
import cn.evchar.proxy.aop.RealSubject;
import cn.evchar.proxy.aop.Subject;
import net.sf.cglib.proxy.Enhancer;
public class Client {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
// 目标对象
enhancer.setSuperclass(RealSubject.class);
// 织入代码
enhancer.setCallback(new DemoMethodInterceptor());
// 生成 代理类
Subject subject = (Subject) enhancer.create();
subject.hello();
subject.request();
}
}
二、Cglib 与JDK 动态代理比较
1、JDK只能针对有接口的类的接口方法进行动态代理
2、Cglib基于继承来实现代理,无法对static,final 类进行代理
3、Cglib基于继承来实现代理,无法对private,static 方法进行代理
4、反之JDK 不能对private 进行代理