Spring AOP通知执行原理

1. AOP的核心概念

  • 切面(Aspect):似于 Java 中的类声明,常用于应用中配置事务或者日志管理。一般使用 @Aspect 注解或者 <aop:aspect> 来定义一个切面。
  • 连接点(Join Point):程序执行中的特定点,比如方法执行、处理一个异常等。
  • 切点(Pointcut):通过一种规则匹配的正则表达式,当有连接点可以匹配到切点时,就会触发改切点相关联的指定通知。
  • 通知(Advice):在切面中某个连接点采取的动作,通知方式也有5种:
    • around(环绕通知):前后都加
    • before(前置通知)
    • after(后置通知)
    • exception(异常通知)
    • return(返回通知)
  • 织入(Weaving):链接切面和目标对象创建一个通知对象的过程。

AOP其实就是一种编程思想,而这上面的这个点就是编程的具体实现规范。

一个应用中可以有多种通知方式所以在AOP中引入一种设计模式责任链模式通过这这种模式来顺序执行每一个通知当然也可以使用@Order注解,配置数字越小,越先执行。

2. AOP的执行过程

准备demo

@Component
public class AopTest {

    public void log(){
        System.out.println("正常执行方法。。。。。。。。。。。");
    }
}
@Component
@Aspect
public class AspectTest {

    @Pointcut("execution(*  com.test.*.service.AopTest.*(..))")
    public void pointLog(){

    }

    @Before("pointLog()")
    public void before(){
        System.out.println("执行方法之前。。。。。。before");
    }

    @After("pointLog()")
    public void after(){
        System.out.println("执行方法之后。。。。。。after");
    }

}

进入到DynamicAdvisedInterceptor 这个静态内部类中的intercept方法。

private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable {
        @Override
        @Nullable
        public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
            。。。
                // 从advised中 获取配置好的AOP的通知方法
                List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
                Object retVal;
                //如果没有通知方法则调用target对象的方法,显然chain不为空则走else逻辑
                if (chain.isEmpty() && CglibMethodInvocation.isMethodProxyCompatible(method)) {

                    Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
                    try {
                        retVal = methodProxy.invoke(target, argsToUse);
                    }
                    catch (CodeGenerationException ex) {
                        CglibMethodInvocation.logFastClassGenerationFailure(method);
                        retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
                    }
                }
                else {
                  //通过CglibMethodInvocation来启动advice通知,proceed()通过调用super.proceed();
                    retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
                }
                retVal = processReturnType(proxy, target, method, retVal);
                return retVal;
            }
            。。。
        }
    }

进入到ReflectiveMethodInvocation 中的proceed()方法

public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {
        。。。

 /**
  * Index from 0 of the current interceptor we're invoking.
  * -1 until we invoke: then the current interceptor.
  */
 private int currentInterceptorIndex = -1;

 // 省略其他的方法

 @Override
 @Nullable
 public Object proceed() throws Throwable {
    // 从索引为-1的拦截器开始调用,并且按顺序递增,如果整个List chain中调用完毕,则开始调用target的函数
    // 具体的实现方式在AOPUtils.invokeJoinpointUsingRefection方法中,其实就是通过反射实现目标方法
  if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
   return invokeJoinpoint();
  }
  // 获取下一个需要执行的拦截器,沿着定义好的interceptorOrInterceptionAdvice的链进行处理
  //在new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed()时,
  //已经将通知方法传入到interceptorsAndDynamicMethodMatchers中。
  Object interceptorOrInterceptionAdvice =
    this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
  if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
      // 对拦截器进行动态匹配,如果和定义的pointcut匹配 则就会执行当前的这个advice
   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 {
  //普通拦截器,直接调用拦截器,将当前的this(CglibMethodInvocation)作为参数保证当前实例中调用链的执行
    //这里就利用到了责任链模式,进行循环调用,直到所有通知执行完成
   return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
  }
 }
}

Spring中的五种通知,首先是通过具Spring容器的启动过程获取到具体的通知,在调用对象时,通过动态代理ASM技术,把需要执行的advice先全部放在一个chain对象的集合中,为了保证整个链的调用默认会先调用ExposeInvocationInterceptor去触发整个链式执行,在执行完每一个advice时后都会再次回到super的proceed方法中,执行下一个advice,在执行不同的advice时有对应的切面通知方法,当所有的advice执行完毕再通过cglib的FastClass机制调用目标方法

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容