Spring源码之AOP原理(下)

SpringAOP的实现有 jdk 动态代理和 cglib 代理,对应的核心类是 JdkDynamicAopProxy 和CglibAopProxy。
先来看 JdkDynamicAopProxy,找到它的 invoke方法,上码:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object oldProxy = null; boolean setProxyContext = false; // 最终操作的是 TargetSource对象 TargetSource targetSource = this.advised.targetSource; Object target = null; try { // 不代理 equals 和 hashCode 方法,调用 JdkDynamicAopProxy中的equal比较和hashCode方法 if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) { return equals(args[0]); } else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) { return hashCode(); } else if (method.getDeclaringClass() == DecoratingProxy.class) { return AopProxyUtils.ultimateTargetClass(this.advised); } else if (!this.advised.opaque && method.getDeclaringClass().isInterface() && method.getDeclaringClass().isAssignableFrom(Advised.class)) { // 如果 method是在 advised中声明的,则把 method转到 advised对象中使用 return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args); }Object retVal; if (this.advised.exposeProxy) { // 如果暴露代理对象,则把proxy设置到 ThreadLocal 中,线程内可共享该对象 oldProxy = AopContext.setCurrentProxy(proxy); setProxyContext = true; }target = targetSource.getTarget(); Class targetClass = (target != null ? target.getClass() : null); // 获取方法的拦截器链 List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); if (chain.isEmpty()) { // 拦截器链为空,则适配参数,直接调用目标方法 Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args); retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse); } else { // 创建 ReflectiveMethodInvocation,去执行前置、后置等增强器 MethodInvocation invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain); // 驱动执行所有拦截器 retVal = invocation.proceed(); }// 返回值处理 Class returnType = method.getReturnType(); if (retVal != null && retVal == target && returnType != Object.class && returnType.isInstance(proxy) &&!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) { retVal = proxy; } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) { throw new AopInvocationException( " ……"); } return retVal; } finally { …… }
我们来重点分析 ReflectiveMethodInvocation#proceed() 方法:
public Object proceed() throws Throwable { // 拦截器执行完了,就执行目标对象的目标方法 if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) { return invokeJoinpoint(); }// 获取责任链下一个 MethodInterceptor, 对目标方法进行增强处理 Object interceptorOrInterceptionAdvice =this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex); if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) { InterceptorAndDynamicMethodMatcher dm =(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice; Class targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass()); // 方法动态匹配成功,才进行增强处理 if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) { return dm.interceptor.invoke(this); } else { // 动态匹配失败,跳过当前拦截器,跳到下一个 return proceed(); } } else { // 不需要动态匹配,则直接调用 MethodInterceptor 的invoke方法 return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this); } }

我们来看 ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this) ,这里是每个interceptor都去invoke一遍,我们先看 MethodBeforeAdviceInterceptor#invoke()
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {private final MethodBeforeAdvice advice; public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; }@Override @Nullable public Object invoke(MethodInvocation mi) throws Throwable { // 先执行 MethodBeforeAdvice 这个 advice,而advice.before 的这个before, //正是我们定义的前置通知的方法体 this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis()); // 再递归执行 MethodInvocation return mi.proceed(); } }

接着再来看 AfterReturningAdviceInterceptor#invoke()
public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {private final AfterReturningAdvice advice; public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; }@Override @Nullable public Object invoke(MethodInvocation mi) throws Throwable { //先执行中间的 MethodInvocation,比如 目标方法 Object retVal = mi.proceed(); // 再执行 AfterReturningAdvice advice的 afterReturning(),这个 // afterReturning() 就是我们定义的后置处理的方法体 this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis()); return retVal; } }

各位看官,到这里是不是很明了了。简而言之,就是遍历所有的增强器(拦截器),有前置增强器就先执行它,接着执行目标方法,再执行后置增强器。就是辣么竿丹~~
【Spring源码之AOP原理(下)】CglibAopProxy 也类似,最终也是调用 ReflectiveMethodInvocation#proceed()~~
各位看官,下节更精彩,点个赞,年薪百万不是梦~

    推荐阅读