Spring AOP从原理到源码(四)

上一节Spring AOP从原理到源码(三)讲述了代理对象的创建过程,本小节关注方法调用的拦截过程。

2. 调用方法的拦截

调用方法拦截主要是将创建阶段中加入的Advisor(或者Advice等)转换成拦截器(MethodInterceptor)链,然后利用责任链模式,逐个调用拦截器链中的拦截器,对被代理方法进行增强。
下面我们来看看调用了proxy.doService方法后会发生什么。
这里我们只关注JdkDynamicAopProxy产生的代理对象,通过Cglib产生的代理对象同理,读者举一反三即可,不做赘述。
我们都知道,当代理对象被拦截时,都会调用InvocationHandler#invoke方法,所以我们关注JdkDynamicAopProxy#invoke,这段代码内容很多,关注有注释的地方即可。

/**
    * Implementation of {@code InvocationHandler.invoke}.
    * <p>Callers will see exactly the exception thrown by the target,
    * unless a hook method throws an exception.
    */
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    MethodInvocation invocation;
    Object oldProxy = null;
    boolean setProxyContext = false;

    // 从配置里把封装了目标对象的TargetSource拿出来
    TargetSource targetSource = this.advised.targetSource;
    Object target = null;

    try {
        if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
            // The target does not implement the equals(Object) method itself.
            return equals(args[0]);
        }
        else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
            // The target does not implement the hashCode() method itself.
            return hashCode();
        }
        else if (method.getDeclaringClass() == DecoratingProxy.class) {
            // There is only getDecoratedClass() declared -> dispatch to proxy config.
            return AopProxyUtils.ultimateTargetClass(this.advised);
        }
        else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
                method.getDeclaringClass().isAssignableFrom(Advised.class)) {
            // Service invocations on ProxyConfig with the proxy config...
            return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
        }

        Object retVal;

        if (this.advised.exposeProxy) {
            // Make invocation available if necessary.
            oldProxy = AopContext.setCurrentProxy(proxy);
            setProxyContext = true;
        }

        // Get as late as possible to minimize the time we "own" the target,
        // in case it comes from a pool.
        target = targetSource.getTarget();
        Class<?> targetClass = (target != null ? target.getClass() : null);

        // Get the interception chain for this method.
        // 获取拦截器链,还记得在创建代理对象过程中的advisors吗?
        // 这里就是把advisors中会拦截现在这个方法(method)的Advisor封装成List<MethodInterceptor>
        /**
        * 什么叫会拦截现在这个方法?
        *   还记得PointcutAdvisor吗?里面有ClassFilter和MethodMatcher,用来匹配是否需要拦截
        */
        List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

        // Check whether we have any advice. If we don't, we can fallback on direct
        // reflective invocation of the target, and avoid creating a MethodInvocation.
        // 拦截器链为空的话,通过反射直接调用目标方法即可
        if (chain.isEmpty()) {
            // We can skip creating a MethodInvocation: just invoke the target directly
            // Note that the final invoker must be an InvokerInterceptor so we know it does
            // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
            Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
            retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
        }
        else {
            // We need to create a method invocation...
            // 创建一个MethodInvocation,封装chain,完成责任链模式
            invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
            // Proceed to the joinpoint through the interceptor chain.
            // proceed方法负责逐个推进chain,一个个调用
            retVal = invocation.proceed();
        }

        // Massage return value if necessary.
        Class<?> returnType = method.getReturnType();
        if (retVal != null && retVal == target &&
                returnType != Object.class && returnType.isInstance(proxy) &&
                !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
            // Special case: it returned "this" and the return type of the method
            // is type-compatible. Note that we can't help if the target sets
            // a reference to itself in another returned object.
            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()) {
            // Must have come from TargetSource.
            targetSource.releaseTarget(target);
        }
        if (setProxyContext) {
            // Restore old proxy.
            AopContext.setCurrentProxy(oldProxy);
        }
    }
}

这个方法我们重点关注3个地方:

  1. 拦截器链的获取;
  2. 责任链(MethodInvocation)的构建。
  3. 责任链的执行,即目标方法执行过程中的增强。

this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass)

/**
    * Determine a list of {@link org.aopalliance.intercept.MethodInterceptor} objects
    * for the given method, based on this configuration.
    * @param method the proxied method
    * @param targetClass the target class
    * @return List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers)
    */
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
    MethodCacheKey cacheKey = new MethodCacheKey(method);
    // 如果这个方法以及被拦截过,直接从缓存中获取即可
    List<Object> cached = this.methodCache.get(cacheKey);
    if (cached == null) {
        // 通过DefaultAdvisorChainFactory来获取到拦截器链
        cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
                this, method, targetClass);
        this.methodCache.put(cacheKey, cached);
    }
    return cached;
}

// DefaultAdvisorChainFactory.java
@Override
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
        Advised config, Method method, @Nullable Class<?> targetClass) {

    // This is somewhat tricky... We have to process introductions first,
    // but we need to preserve order in the ultimate list.
    // interceptorList最大长度也就是advisors.lenth,也就是所有advisor都拦截这个方法
    List<Object> interceptorList = new ArrayList<>(config.getAdvisors().length);
    Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
    boolean hasIntroductions = hasMatchingIntroductions(config, actualClass);
    AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();

    // 逐个遍历advisor
    for (Advisor advisor : config.getAdvisors()) {
        if (advisor instanceof PointcutAdvisor) {// PointcutAdvisor拦截能力最细化
            // Add it conditionally.
            PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
            // 先看看ClassFilter#mathches能否匹配
            if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
                // 通过advice获取到Interceptors
                MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
                MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
                // 通过MethodMatcher#matches看看这个方法是否需要拦截
                if (MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {
                    // 非重点:返回true的话,还有根据传入参数看看是否需要拦截
                    if (mm.isRuntime()) {
                        // Creating a new object instance in the getInterceptors() method
                        // isn't a problem as we normally cache created chains.
                        for (MethodInterceptor interceptor : interceptors) {
                            interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
                        }
                    }
                    else {
                        // 加入到interceptorList里
                        interceptorList.addAll(Arrays.asList(interceptors));
                    }
                }
            }
        }
        else if (advisor instanceof IntroductionAdvisor) {// IntroductionAdvisor的话只有类匹配即可,所有方法都拦截
            IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
            if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
                Interceptor[] interceptors = registry.getInterceptors(advisor);
                interceptorList.addAll(Arrays.asList(interceptors));
            }
        }
        else {
            Interceptor[] interceptors = registry.getInterceptors(advisor);
            interceptorList.addAll(Arrays.asList(interceptors));
        }
    }

    return interceptorList;
}

// DefaultAdvisorAdapterRegistry.java
@Override
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
    /**
    * 非重点:
    *   this.adapters中包含了3个adapter:MethodBeforeAdviceAdapter、AfterReturningAdviceAdapter、ThrowsAdviceAdapter
    *   所以最多的情况也就是,advice满足所有adapter,即一个advice对应3个MethodInterceptor
    */
    List<MethodInterceptor> interceptors = new ArrayList<>(3);
    Advice advice = advisor.getAdvice();
    // 如果advice本身也implement了MethodInterceptor,先添加进去
    if (advice instanceof MethodInterceptor) {
        interceptors.add((MethodInterceptor) advice);
    }
    // 适配器模式
    for (AdvisorAdapter adapter : this.adapters) {
        if (adapter.supportsAdvice(advice)) {
            interceptors.add(adapter.getInterceptor(advisor));
        }
    }
    if (interceptors.isEmpty()) {
        throw new UnknownAdviceTypeException(advisor.getAdvice());
    }
    return interceptors.toArray(new MethodInterceptor[0]);
}

为了读者思路的流畅性,如果还没很明白前面说的内容,下面这段可以先不看,先把流程理顺
这里多说一下从advisor中获取interceptors的方法(DefaultAdvisorAdapterRegistry#getInterceptors)中的适配器模式。
对于Advice来说,有很多种:BeforAdviceAfterAdviceThrowsAdvice……在实现上,也有非常多的实现:AbstractAspectJAdvice及其子类,Interceptor及其子类……如果把这些统一起来,封装到MethodInterceptor里,就需要适配器了。可以看到DefaultAdvisorAdapterRegistry在构造方法中添加了3种适配器:MethodBeforeAdviceAdapterAfterReturningAdviceAdapterThrowsAdviceAdapter
下面具体看看adapter#getInterceptor做了什么,以MethodBeforeAdviceAdapter为例:


class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {

@Override
public boolean supportsAdvice(Advice advice) {
    // 如果advice属于MethodBeforAdvice就能支持,才能调用下面的getInterceptor方法
    return (advice instanceof MethodBeforeAdvice);
}

@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
    MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
    // 把advice封装起来,待调用的时候使用
    return new MethodBeforeAdviceInterceptor(advice);
}

}

new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain)

这个方法就是构建责任链,源码没什么特别的,不做特别说明。

invocation.proceed()

责任链的执行,很明显就是把上面的拦截器一个个拿出来,调用MethodInterceptor#invoke方法

@Override
@Nullable
public Object proceed() throws Throwable {
    //  We start with an index of -1 and increment early.
    // 所有MethodInterceptor都遍历完了,直接调用目标方法
    if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
        return invokeJoinpoint();
    }

    // 获取到下一个待调用是拦截器(MethodInterceptor)
    Object interceptorOrInterceptionAdvice =
            this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
    // 如果是动态的拦截器(即MethodMather#isRuntime == true的)还要根据传入方法的参数来拦截
    if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
        // Evaluate dynamic method matcher here: static part will already have
        // been evaluated and found to match.
        InterceptorAndDynamicMethodMatcher dm =
                (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
        if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
            return dm.interceptor.invoke(this);
        }
        else {
            // Dynamic matching failed.
            // Skip this interceptor and invoke the next in the chain.
            return proceed();
        }
    }
    // 正常情况,直接拦截
    else {
        // It's an interceptor, so we just invoke it: The pointcut will have
        // been evaluated statically before this object was constructed.
        // 调用MethodInterceptor#invoke
        return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
    }
}

这个方法的逻辑就是,拦截器链还有没执行完的就拿出来继续调用invoke方法,执行完了就直接调用被代理对象的目标方法。
重点看看return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);(注意这里传入了this,也就是把ReflectiveMethodInvocation实例又传进去了),以MethodBeforeAdviceInterceptor#invoke为例`:

// MethodBeforeAdviceInterceptor.java
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
    // 真正的方法增强在这里完成
    this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
    // 推进到下一个MethodInterceptor执行,mi就是之前传进来的this,也就是ReflectiveMethodInvocation,所以又会回到ReflectiveMethodInvocation#proceed
    // 大白话就是:触发下一个拦截器,或者调用目标方法
    return mi.proceed();
}

通过这个方法可以看到,调用了之后又会回到ReflectiveMethodInvocation#proceed方法继续执行链式调用,一直到最后调用目标方法。
至此,拦截过程执行完毕。

源码总结

通过看源码,可以得出结论:

  1. ProxyFactory核心就是两段:
  • 创建代理对象
  • 拦截过程中的调用链执行
  1. 对于代理对象的创建,其实就是把Advisor(s)和目标对象封装在一起
  2. 对于拦截过程,就是把Advisor(s)转换成List<MethodInterceptor>,然后封装成责任链(ReflectiveMethodInvocation),通过ReflectiveMethodInvocation#proceed方法推进拦截器(MethodInterceptor#invoke)的执行,最后是目标方法。
  3. 所以对读者来说,只要清楚的核心过程,又知道里面出现的AdviceAdvisorPointcutMethodInterceptorMethodInvocation分别是什么,理解源码完全没有难度。

大礼送上

带源码注释的代理送给大家,地址

小结

文章讲到这里,相信大家对spring aop的核心过程已经有所了解了,对于ProxyFactoryBean,先简单讲讲原理,未来有时间的话再考虑写文章分析,主要是原理都一样的,看到这里读者应该都有能力分析。
ProxyFactoryProxyFactoryBean的最大区别就是前者是编程式创建代理,而后者是声明式的创建代理,如果了解spring里的FactoryBean就知道了,直接看ProxyFactoryBean#getObject方法即可。

对于完成的spring aop流程,无非就是封装了ProxyFactory,没有什么特别的,在容器启动的时候,创建bean,然后通过后置处理器看看是否需要代理,需要代理的话,找到它的切面(Advisor),然后创建代理。就这么简单。

总结

总结一下Spring AOP的学习方法。所谓“授人以鱼不如授人以渔”,之前所看的所有文章都在讲源码,讲得都挺好,我开始看这个的时候也是这么看源码的,能看懂,但不深刻,大概是方法还不够到位。其实spring aop的源码也不算很难,掌握了学习方法和一些对应的设计模式(内功)即可。
下面说说个人认为比较好的学习方法,如果大家有好的方法,也欢迎不吝赐教。

  1. 了解核心类:AdvicePointcutAdvisorPointcutAdvisorInterceptor,及其对应的继承关系;
  2. 知道aop的两个核心过程:代理创建过程、方法调用拦截过程。
  3. ProxyFactory开始看起ProxyFactory开始看起ProxyFactory开始看起
  4. 最后看ProxyFactoryBean(这是ProxyFactory + FactoryBean的结合)和EnableAspectJAutoProxy(这是对ProxyFactory的封装)。

转载请说明出处

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

推荐阅读更多精彩内容