SpringAOP中的动态代理

Spring代理实际上是对JDK代理和CGLIB代理做了一层封装,并且引入了AOP概念:Aspect、advice、joinpoint等等,同时引入了AspectJ中的一些注解@pointCut,@after,@before等等.Spring Aop严格的来说都是动态代理,和Aspectj的关系并不大。

Spring代理中org.springframework.aop.framework.ProxyFactory是关键,一个简单的使用API编程的Spring AOP代理如下:

ProxyFactory proxyFactory =new ProxyFactory(Calculator.class, new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                return null;
            }
        });
        proxyFactory.setOptimize(false);
        //得到代理对象
        proxyFactory.getProxy();

在调用getProxy()时,会优先得到一个默认的DefaultAopProxyFactory.这个类主要是决定到底是使用JDK代理还是CGLIB代理:

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        //optimize 优化,如上列代码编程true会默认进入if
        //ProxyTargetClass 是否对具体类进行代理
        //判断传入的class 是否有接口。如果没有也会进入选择
        if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
            Class targetClass = config.getTargetClass();
            if (targetClass == null) {
                throw new AopConfigException("TargetSource cannot determine target class: " +
                        "Either an interface or a target is required for proxy creation.");
            }
            //如果目标是接口的话还是默认使用JDK
            if (targetClass.isInterface()) {
                return new JdkDynamicAopProxy(config);
            }
            return CglibProxyFactory.createCglibProxy(config);
        }
        else {
            return new JdkDynamicAopProxy(config);
        }
    }

可以看见一些必要的信息,我们在使用Spring AOP的时候通常会在XML配置文件中设置<aop:aspectj-autoproxy proxy-target-class="true"> 来使用CGlib代理。现在我们可以发现只要三个参数其中一个为true,便可以有机会选择使用CGLIB代理。但是是否一定会使用还是得看传入的class到底是个怎样的类。如果是接口,就算开启了这几个开关,最后还是会自动选择JDK代理。

JdkDynamicAopProxy这个类实现了InvokeHandler接口,最后调用getProxy():

public Object getProxy(ClassLoader classLoader) {
        //...
        //返回代理对象
        return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
    }

那么JdkDynamicAopProxy中的invoke方法就是最核心的方法了(实现了InvokeHandler接口):

/**
     * Implementation of {@code InvocationHandler.invoke}.
     * <p>Callers will see exactly the exception thrown by the target,
     * unless a hook method throws an exception.
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MethodInvocation invocation;
        Object oldProxy = null;
        boolean setProxyContext = false;
 
        TargetSource targetSource = this.advised.targetSource;
        Class targetClass = null;
        Object target = null;
 
        try {
            //是否实现equals和hashCode,否则不代理。因为JDK代理会默认代理这两个方法
            if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
                return equals(args[0]);
            }
            if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
                return hashCode();
            }
            //不能代理adviser接口和子接口自身
            if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
                    method.getDeclaringClass().isAssignableFrom(Advised.class)) {
                return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
            }
 
            Object retVal;
            //代理类和ThreadLocal绑定
            if (this.advised.exposeProxy) {
                // Make invocation available if necessary.
                oldProxy = AopContext.setCurrentProxy(proxy);
                setProxyContext = true;
            }
 
            //合一从TargetSource得到一个实例对象,可实现接口获得
            target = targetSource.getTarget();
            if (target != null) {
                targetClass = target.getClass();
            }
        
            //得到拦截器链
            List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
            //如果没有定义拦截器链。直接调用方法不进行代理
            if (chain.isEmpty()) {
                retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args);
            }
            else {
                // We need to create a method invocation...
                invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
                //执行拦截器链。通过proceed递归调用
                // Proceed to the joinpoint through the interceptor chain.
                retVal = invocation.proceed();
            }
 
            // Massage return value if necessary.
            Class<?> returnType = method.getReturnType();
            if (retVal != null && retVal == target && returnType.isInstance(proxy) &&
                    !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
                //如果返回值是this 直接返回代理对象本身
                retVal = proxy;
            } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
                throw new AopInvocationException("Null return value from advice does not match primitive return type for: " + method);
            }
            return retVal;
        }
        finally {
            if (target != null && !targetSource.isStatic()) {
                targetSource.releaseTarget(target);
            }
            if (setProxyContext) {
                AopContext.setCurrentProxy(oldProxy);
            }
        }
    }

下面来分析整个代理的拦截器是怎么运行的,ReflectiveMethodInvocation这个类的proceed()方法负责递归调用所有的拦截的织入。

public Object proceed() throws Throwable {
        //list的索引从-1开始。 
                if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
        //所有interceptor都被执行完了,直接执行原方法
            return invokeJoinpoint();
        }
        //得到一个interceptor。不管是before还是after等织入,都不受在list中的位置影响。
        Object interceptorOrInterceptionAdvice =
                this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
        //....
        //调用invoke方法
            return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
        }
    }

需要注意的是invoke方法中传入的是this。在MethodInvocation中又可以调用procced来实现递归调用。比如像下面这样:

new MethodInterceptor() {
            @Override
public Object invoke(MethodInvocation invocation) throws Throwable {
              Object re= invocation.proceed();
              return re;
            }
        }

那么要实现织入,只需要控制织入的代码和调用proceed方法的位置,在Spring中的before织入是这样实现的:

public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable {
 
    private MethodBeforeAdvice advice;
 
    public Object invoke(MethodInvocation mi) throws Throwable {
        //调用before实际代码
        this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
        //继续迭代
        return mi.proceed();
    }

afterRuturning是这样实现的:

public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {
 
    private final AfterReturningAdvice advice;
 
    public Object invoke(MethodInvocation mi) throws Throwable {
        Object retVal = mi.proceed();
        //只要控制和mi.proceed()调用的位置关系就可以实现任何状态的织入效果
        this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
        return retVal;
    }

总结:
Spring AOP封装了JDK和CGLIB的动态代理实现,同时引入了AspectJ的编程方式和注解。使得可以使用标准的AOP编程规范来编写代码外,还提供了多种代理方式选择。可以根据需求来选择最合适的代理模式。同时Spring也提供了XML配置的方式实现AOP配置。可以说是把所有想要的都做出来了,Spring是在平时编程中使用动态代理的不二选择.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 说明:本文主要内容来自慕课网。配合视频食用口味更佳。主要是顺着已经学习的视频顺序总结一遍,以深化理解和方便日后复习...
    stoneyang94阅读 831评论 3 5
  • 1.1 spring IoC容器和beans的简介 Spring 框架的最核心基础的功能是IoC(控制反转)容器,...
    simoscode阅读 6,633评论 2 22
  • 清洁是皮肤保养的基础。护肤时,清洁卸妆的重要性往往被忽视,殊不知一切营养品若要发挥其功效,都必须进入到经过彻底清洁...
    卓别林unhp阅读 134评论 0 0
  • 24岁的婉莹,淡眉如秋水,玉肌伴轻风,是个蕴含古典气质的美女。 25岁的志强,脸如雕刻俊,气质比明星,是个性格开朗...
    华玉珺阅读 503评论 4 6