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

探秘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 进行代理

三、Spring对两种实现选择

输入图片说明

输入图片说明

转载于:https://my.oschina.net/u/3136594/blog/1556218

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值