Spring AOP MethodInvocation

所有文章已迁移至csdn,csdn个人主页bugpool.blog.csdn.net

Spring AOP源码目录

Spring AOP源码01:Jdk动态代理底层源码
Spring AOP源码02:ProxyFactory
Spring AOP源码03:JdkDynamicAopProxy
Spring AOP源码04:MethodInvocation 拦截器调用
Spring AOP源码05:DefaultAdvisorAutoProxyCreator
Spring期末考压轴题:当Spring AOP遇上循环依赖
git注释源码地址:https://github.com/chaitou/spring-framework-master.git

前言

通过对JdkDynamicAopProxyinvoke方法的探究,发现invoke的核心是:

  1. 由匹配当前方法的advisor,例如与当前方法所匹配的所有before、afterReturning等增强,再将这些增强组成拦截器链
// 生产拦截器链
MethodInvocation invocation =
      new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// 执行拦截器链
retVal = invocation.proceed();
  1. 调用拦截器链,使其能够按before -> method -> after -> afterReturning的顺序链式调用。但是在源代码中,看到的并不是for循环的调用,而是只有invoke(this)这一行关键代码。而这一行代码是如何保证各个增强的有序调用的呢?我们将带着这个问题来探究一下拦截器的源码。典型的职责链模式
public Object proceed() throws Throwable {
      // We start with an index of -1 and increment early.
      if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
         return invokeJoinpoint();
      }

      Object interceptorOrInterceptionAdvice =
            this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
      if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
         // 省略动态匹配,不是本节重点 ...
      }
      else {
         // It's an interceptor, so we just invoke it: The pointcut will have
         // been evaluated statically before this object was constructed.
         // 普通拦截器,直接触发
         return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
      }
}

源码分析

代码示例

Service、ServiceImpl

public interface UserService {
    public void findUser();
}

@Component
public class UserServiceImpl implements UserService {
    public void findUser() {
        System.out.println("findUser");
    }
}

2个带order的切面类

@Component
@Aspect
public class LogAspect1 implements Ordered {

    @Pointcut("execution(* aop.UserServiceImpl.findUser())")
    public void point() {
    }

    @Before("point()")
    public void before(){
        System.out.println("log before1...");
    }

    @AfterReturning("point()")
    public void afterReturning() { System.out.println("log after returning1..."); }

    @Override
    public int getOrder() {
        return 1;
    }
}
@Component
@Aspect
public class LogAspect2 implements Ordered {

    @Pointcut("execution(* aop.UserServiceImpl.findUser())")
    public void point() {
    }

    @Before("point()")
    public void before(){
        System.out.println("log before2...");
    }

    @AfterReturning("point()")
    public void afterReturning() { System.out.println("log after returning2..."); }

    @Override
    public int getOrder() {
        return 2;
    }
}

xml配置,自动扫描、开启AOP而已



测试

    @Test
    public void test1() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("aop.xml");
        UserService userService = (UserService) applicationContext.getBean("userServiceImpl", UserService.class);
        userService.findUser();
    }

结果

log before1...
log before2...
findUser
log after returning2...
log after returning1...

执行过程

看执行结果已经可以得出,拦截器执行过程跟栈差不多,先before的后after,大概就是下图所示

aop调用

源码分析

生产拦截器链

// 生产拦截器链
MethodInvocation invocation =
      new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);

首先我们先看一下拦截器链到底长什么样,通过调试代码,查看invocation变量

拦截器链

  1. order的排序在获取切面中就已经做好,在下一节中我们会看到源码,这里不纠结,就是通过回调子类getOrder获取优先级,然后排序
  2. 我们看到同一个order中,afterReturing居然排在了before,这样怎么保证beforeafter之前调用呢?
  3. method方法并不在列表中,又是何时调用method呢?

答案是,控制增强的调用顺序其实由每个拦截器负责,所以我们需要分析MethodBeforeAdviceInterceptorAfterReturningAdviceInterceptor

执行拦截器链

// 执行拦截器链
retVal = invocation.proceed();
public Object proceed() throws Throwable {
      // 初始currentInterceptorIndex为-1,每调用一次proceed就把currentInterceptorIndex+1
      if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
         // 当调用次数 = 拦截器个数时
         // 1. 触发当前method方法
         return invokeJoinpoint();
      }

      Object interceptorOrInterceptionAdvice =
            this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
      if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
         // 省略动态匹配,不是本节重点 ...
      }
      else {
         // It's an interceptor, so we just invoke it: The pointcut will have
         // been evaluated statically before this object was constructed.
         // 2. 普通拦截器,直接触发拦截器invoke方法
         return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
      }
}
  1. 当调用次数 = 拦截器个数时,调用method方法,可能读者会有疑惑?这样method方法不就变成最后调用了吗?想解决这个疑问还是要看拦截器源码才能解决,因此继续往下看
  2. 普通拦截器,直接调用拦截器的invoke方法,所以重点还是在拦截器源码。这里涉及到3种拦截器MethodBeforeAdviceInterceptorAfterReturningAdviceInterceptor我们将重点分析。ExposeInvocationInterceptor是每个拦截器链都会加上的拦截器,用于曝光当前拦截器链到ThreadLocal的,好让同线程下可以共享拦截器链,不是本节重点就不赘述了

MethodBeforeAdviceInterceptor

public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {

    private final MethodBeforeAdvice advice;

    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        // 先调用before方法
        this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
        // 继续链式调用
        return mi.proceed();
    }

}

AfterReturningAdviceInterceptor

public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {

   private final AfterReturningAdvice advice;

   @Override
   public Object invoke(MethodInvocation mi) throws Throwable {
      // 先进行链式调用
      Object retVal = mi.proceed();
      // 再调用afterReturning方法
      this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
      return retVal;
   }

}

看到这里不知道大家是不是有点眉目了,拦截器链执行的顺序正时在各个拦截器的invoke方法中实现的。before会先执行advice增强方法再链式调用,这个比较好理解而after则是先执行链式调用,再调用advice增强方法,也就是一个递归的过程 ,这里灵魂画手出山,画一下调用顺序,相信有助于大家理解。(注:忽视掉ExposeInvocationInterceptor拦截器,只关心before和afterReturing)

拦截器调用原理

你可能感兴趣的:(Spring AOP MethodInvocation)