Spring|Spring AOP从原理到源码(四)

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

/** * Implementation of {@code InvocationHandler.invoke}. * 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 /** * 什么叫会拦截现在这个方法? *还记得PointcutAdvisor吗?里面有ClassFilter和MethodMatcher,用来匹配是否需要拦截 */ List 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 getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class targetClass) { MethodCacheKey cacheKey = new MethodCacheKey(method); // 如果这个方法以及被拦截过,直接从缓存中获取即可 List 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 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 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 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,然后封装成责任链(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的封装)。
【Spring|Spring AOP从原理到源码(四)】转载请说明出处!

    推荐阅读