广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring源码阅读MethodInterceptor解析
  • 794
分享到

Spring源码阅读MethodInterceptor解析

SpringMethodInterceptorSpringMethodInterceptor源码解析 2022-11-13 19:11:05 794人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录概述MethodInterceptor 分析AspectjaroundAdvice 分析AspectJAfterThrowingAdvice 分析AspectJAfterAdvi

概述

上一篇详细分析了 ReflectiveMethodInvocation 中的proceed方法的逻辑,它通过递归的方式,完成拦截器链中增强逻辑的逐层执行。当方法中每次根据索引获取到的当前拦截器需要执行增强逻辑的时候,由于proceed方法并没有直接在方法体内调用自身,而是调用了拦截器的invoke方法,之后拦截器的invoke方法又调用了proceed方法,因此,每一次递归都是通过proceed方法和拦截器的invoke方法共同完成的。

所以,这一篇来分析拦截器的invoke方法,针对 5 种增强类型,拦截器的具体类型也有 5 种,它们的invoke方法实现各不相同,本文会逐个分析。

MethodInterceptor 分析

首先,这 5 种拦截器都是 MethodInterceptor 接口的实现,而invoke方法正是在 MethodInterceptor 接口中定义的。

@FunctionalInterface
public interface MethodInterceptor extends Interceptor {
Object invoke(MethodInvocation invocation) throws Throwable;
}

invoke方法被调用的时候,传入的invocation参数就是之前创建的 ReflectiveMethodInvocation 对象,在invoke方法的具体实现中,正是通过它调用proceed方法完成了递归。

在之前的文章中,分析过 jdkDynamicaopProxy 的invoke方法获取拦截器链的步骤,也从中了解了 5 中增强类型的拦截器的具体类型,它们分别是:

  • 实现了 MethodInterceptor 接口的三个 Advice 实现类 AspectJAroundAdvice / AspectJAfterThrowingAdvice / AspectJAfterAdvice
  • 两个通过适配器封装了 Advice 对象的拦截器类型 MethodBeforeAdviceInterceptor / AfterReturningAdviceInterceptor。

下面进入分析的环节,分析的主要内容是他们的invoke方法。

AspectJAroundAdvice 分析

// org.springframework.aop.aspectj.AspectJAroundAdvice#invoke
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
   if (!(mi instanceof ProxyMethodInvocation)) {
      throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);
   }
   ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;
   ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi);
   JoinPointMatch jpm = getJoinPointMatch(pmi);
   return invokeAdviceMethod(pjp, jpm, null, null);
}

方法中,首先会确保参数传入的mi是否是是 ProxyMethodInvocation 的实现类,根据前面的逻辑,我们知道这里传入参数的对象是之前创建的 ReflectiveMethodInvocation 对象,前面创建 ReflectiveMethodInvocation 对象的时候,我们曾经分析过它的类关系,它是 ProxyMethodInvocation 接口的实现类。因此,这个方法中后续的流程会正常执行。

接下来,通过lazyGetProceedingJoinPoint方法得到了一个 ProceedingJoinPoint 对象pjp,我们看一下这个方法中作了什么。

// org.springframework.aop.aspectj.AspectJAroundAdvice#lazyGetProceedingJoinPoint
protected ProceedingJoinPoint lazyGetProceedingJoinPoint(ProxyMethodInvocation rmi) {
   return new MethodInvocationProceedingJoinPoint(rmi);
}

这里的逻辑,就是将invoke方法传入的 MethodInvocation 参数,通过构造方法,封装成了一个 MethodInvocationProceedingJoinPoint 对象,它的构造方法中除了把参数赋值给成员变量,并无更多的逻辑。

public MethodInvocationProceedingJoinPoint(ProxyMethodInvocation methodInvocation) {
   Assert.notNull(methodInvocation, "MethodInvocation must not be null");
   this.methodInvocation = methodInvocation;
}

回到invoke方法中,下一步是通过getJoinPointMatch方法获取到一个 JoinPointMatch 对象,它会在之后绑定增强方法的参数值时用到。

方法的最后,就是执行invokeAdviceMethod方法,从它的名字可以看出,这里就是执行增强方法的逻辑,我们进入这个方法查看。

// org.springframework.aop.aspectj.AbstractAspectJAdvice#invokeAdviceMethod(org.aspectj.lang.JoinPoint, org.aspectj.weaver.tools.JoinPointMatch, java.lang.Object, java.lang.Throwable)
protected Object invokeAdviceMethod(JoinPoint jp, @Nullable JoinPointMatch jpMatch,
      @Nullable Object returnValue, @Nullable Throwable t) throws Throwable {
   return invokeAdviceMethodWithGivenArgs(argBinding(jp, jpMatch, returnValue, t));
}

这个方法的实现在父类 AbstractAspectJAdvice 中,方法只有一句,就是执行invokeAdviceMethodWithGivenArgs方法并返回结果,在方法的参数中,argBinding用于根据增强方法的参数列表,来绑定执行增强方法的参数值。我们进入invokeAdviceMethodWithGivenArgs方法查看。

// org.springframework.aop.aspectj.AbstractAspectJAdvice#invokeAdviceMethodWithGivenArgs
protected Object invokeAdviceMethodWithGivenArgs(Object[] args) throws Throwable {
   Object[] actualArgs = args;
   if (this.aspectJAdviceMethod.getParameterCount() == 0) {
      actualArgs = null;
   }
   try {
      ReflectionUtils.makeAccessible(this.aspectJAdviceMethod);
      // TODO AopUtils.invokeJoinpointUsingReflection
return this.aspectJAdviceMethod.invoke(this.aspectInstanceFactory.getAspectInstance(), actualArgs);
   }
   catch (IllegalArgumentException ex) {
      throw new AopInvocationException("Mismatch on arguments to advice method [" +
            this.aspectJAdviceMethod + "]; pointcut expression [" +
            this.pointcut.getPointcutExpression() + "]", ex);
   }
   catch (InvocationTargetException ex) {
      throw ex.getTargetException();
   }
}

这里的逻辑就比较简单了,就是获取到当前拦截器中的增强方法,并通过反射执行这个方法。

我们都知道,AspectJAroundAdvice 是环绕增强,也就是在目标方法执行的前后都有增强逻辑,那么,目标方法(或者下一层拦截器)是什么时候调用的呢?可以通过一个例子来分析。

以下是一个典型的环绕增强的方法:

@Around("point()")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    System.out.println("Around Before ...");
    // 被增强的方法
    proceedingJoinPoint.proceed();
    System.out.println("Around After ...");
}

在一个环绕增强的方法中,会通过方法参数中,代表当前连接点的 ProceedingJoinPoint 对象的proceed()来执行目标方法(或者下一层拦截器),其实就是调用了我们上一篇中分析的 ReflectiveMethodInvocation 的proceed方法。而这个方法被调用时,参数中的 ProceedingJoinPoint 的值,是在前面的步骤中,argBinding方法中进行绑定的。

以上就是 AspectJAroundAdvice 中,增强逻辑的执行过程。

AspectJAfterThrowingAdvice 分析

// org.springframework.aop.aspectj.AspectJAfterThrowingAdvice#invoke
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
   try {
      return mi.proceed();
   }
   catch (Throwable ex) {
      if (shouldInvokeOnThrowing(ex)) {
         invokeAdviceMethod(getJoinPointMatch(), null, ex);
      }
      throw ex;
   }
}

在 AspectJAfterThrowingAdvice 中,invoke方法相对更加简单。AspectJAfterThrowingAdvice 是在方法抛出异常后,执行增强逻辑,在invoke方法中,也能很简单地对应到这样的逻辑。

首先,进入方法后会直接执行mi.proceed(),也就是执行 ReflectiveMethodInvocation 的proceed方法的下一层递归,如果后续的执行抛出了异常,则执行catch语句块中的内容,其中就包含了增强逻辑的执行。

不过,在执行增强逻辑之前,还通过shouldInvokeOnThrowing方法进行了一次判断,我们查看方判断的逻辑。

// org.springframework.aop.aspectj.AspectJAfterThrowingAdvice#shouldInvokeOnThrowing
private boolean shouldInvokeOnThrowing(Throwable ex) {
   return getDiscoveredThrowingType().isAssignableFrom(ex.getClass());
}

这里的逻辑比较简单,就是只有抛出的异常是增强方法指定的异常或者其子类的时候,才会执行异常抛出后的增强逻辑,否则,不执行增强逻辑,直接将异常抛出。

那如何在增强方法上指定异常的类型呢,我们还是看一个例子:

@AfterThrowing(value = "point()", throwing = "ex")
public void afterThrowing(JoinPoint joinPoint, Exception ex) {
    System.out.println("AfterThrowing...");
}

在以上的例子中,@AfterThrowing注解指定了throwing属性为ex,那么增强方法中,ex参数的类型 Exception 就是指定的异常类型。

回到invoke方法中,执行增强逻辑的方式是调用invokeAdviceMethod方法,与环绕增强的增强方法执行时调用的invokeAdviceMethod相比,这里少一个参数,也就是 JoinPoint 参数,这是因为 AspectJAfterThrowingAdvice 类型的增强方法并不需要在增强逻辑中处理目标方法的调用,我们进入这个重载方法查看代码。

protected Object invokeAdviceMethod(
      @Nullable JoinPointMatch jpMatch, @Nullable Object returnValue, @Nullable Throwable ex)
      throws Throwable {
   return invokeAdviceMethodWithGivenArgs(argBinding(getJoinPoint(), jpMatch, returnValue, ex));
}

发现,逻辑上并没有什么区别,就只是少绑定一个参数而已。

另外,这里还有一点需要留意,在调用invokeAdviceMethod方法时,会将抛出的异常对象作为参数传入,这也很好理解 ,因为增强方法中可以包含异常对象的参数。

以上是 AspectJAfterThrowingAdvice 中,增强逻辑的执行过程。

AspectJAfterAdvice 分析

// org.springframework.aop.aspectj.AspectJAfterAdvice#invoke
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
   try {
      return mi.proceed();
   }
   finally {
      invokeAdviceMethod(getJoinPointMatch(), null, null);
   }
}

在 AspectJAfterAdvice 中,invoke方法的逻辑更加简单。我们知道,后置增强会在目标方法执行之后再执行,而且,无论是否抛出了一场,都会执行。因此,在invoke方法中,会先执行 MethodInvocation 的proceed方法,然后,在finally语句块中,执行增强方法。

增强方法的执行,仍然是通过invokeAdviceMethod方法,这里就不再介绍了。

以上是 AspectJAfterAdvice 中,增强逻辑的执行过程。

MethodBeforeAdviceInterceptor 分析

// org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor#invoke
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
   this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
   return mi.proceed();
}

前置增强 MethodBeforeAdvice 与上述的三种增强不同,它并不是 MethodInterceptor 的实现类,因此,其对应的拦截器是封装了 MethodBeforeAdvice 的 MethodBeforeAdviceInterceptor。

因为前置增强是在目标方法执行前执行,既然在执行前,则不会涉及到目标方法的异常和返回值,可以说,前置增强的逻辑和目标方法的逻辑,相对比较独立。因此,在上面的invoke方法中,分别执行两者即可。

这里我们看一下前置增强方法逻辑的执行。首先,advice成员变量就是在 MethodBeforeAdviceInterceptor 中封装的 MethodBeforeAdvice 对象,我们找到它的before方法,具体实现逻辑在 AspectJMethodBeforeAdvice 中。

// org.springframework.aop.aspectj.AspectJMethodBeforeAdvice#before
@Override
public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
   invokeAdviceMethod(getJoinPointMatch(), null, null);
}

可以看到,这里依然是通过invokeAdviceMethod方法来执行增强逻辑的,与之前的几种增强方法对应的执行逻辑相同。

以上是 MethodBeforeAdviceInterceptor 中,增强逻辑的执行过程。

AfterReturningAdviceInterceptor 分析

// org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor#invoke
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
   Object retVal = mi.proceed();
   this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
   return retVal;
}

在 AfterReturningAdviceInterceptor 的invoke方法中,会先执行 MethodInvocation 的proceed方法,并获取返回值,然后,在上一步执行没有发生异常的情况下,执行增强方法,最后将proceed的返回值返回。

增强方法通过调用advice成员变量的afterReturning来完成,这里有一点要留意的是,增强逻辑的执行,会将上一步proceed得返回值作为参数传入。我们进入afterReturning方法。

// org.springframework.aop.aspectj.AspectJAfterReturningAdvice#afterReturning
@Override
public void afterReturning(@Nullable Object returnValue, Method method, Object[] args, @Nullable Object target) throws Throwable {
   if (shouldInvokeOnReturnValueOf(method, returnValue)) {
      invokeAdviceMethod(getJoinPointMatch(), returnValue, null);
   }
}

具体的实现逻辑在 AspectJAfterReturningAdvice 中,在执行具体的增强逻辑之前,还会进行一次判断,这里的逻辑跟 AspectJAfterThrowingAdvice 中判断异常的逻辑非常相似,shouldInvokeOnReturnValueOf方法会判断目标方法的返回值类型跟增强方法上面声明的返回值类型是否匹配,只有匹配的情况下,才会执行增强逻辑。

在增强方法上声明返回值类型的方法参考下面的例子:

@AfterReturning(value = "point()", returning = "o")
public void afterReturning(Object o) {
    System.out.println("AfterReturning...");
}

增强方法依然是通过 invokeAdviceMethod 执行的,只不过这里要讲上一步的返回值传入,以便增强方法能够通过参数绑定获得到这个值。

以上是 AfterReturningAdviceInterceptor 中,增强逻辑的执行过程。

总结

本文详细分析了 Spring AOP 中五种增强类型对应的拦截器中增强方法的执行逻辑,结合上一篇中分析的 ReflectiveMethodInvocation 中proceed方法的执行逻辑,就组成了完整的拦截器链递归调用的逻辑。

以上就是Spring源码阅读MethodInterceptor解析的详细内容,更多关于Spring MethodInterceptor的资料请关注编程网其它相关文章!

--结束END--

本文标题: Spring源码阅读MethodInterceptor解析

本文链接: https://www.lsjlt.com/news/170580.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作