探秘Spring AOP (八) Spring AOP 实现原理 3

探秘Spring AOP

1、Cglib 动态代理实现

  • 一、代理类
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;
    }
}
  • 二、客户端调用方式
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();
    }
}

2、Cglib 与JDK 动态代理比较

一、JDK只能针对有接口的类的接口方法进行动态代理java

二、Cglib基于继承来实现代理,没法对static,final 类进行代理ide

三、Cglib基于继承来实现代理,没法对private,static 方法进行代理代理

四、反之JDK 不能对private 进行代理code

3、Spring对两种实现选择

输入图片说明

输入图片说明

相关文章
相关标签/搜索