Spring Aspect 调用过程

灰太狼 2021-09-11 08:04 269阅读 0赞

主要想了解一下Spring中如何通过切面去动态在方法前后切入多个切入点去实现的。

需要关注的几个点:

  1. 切入点和通知是如何去注册的?(后续补充)
  2. 代理过程中是如何植入这些拦截的?

布置场景

log 日志切入点实现类

  1. /**
  2. * 日志切面
  3. *
  4. * @author Liukx
  5. * @create 2017-12-14 11:21
  6. * @email liukx@elab-plus.com
  7. **/
  8. public class LogAspect {
  9. public LogAspect(){
  10. System.out.println("加载==============logAspect");
  11. }
  12. Logger logger = LoggerFactory.getLogger(LogAspect.class);
  13. public void before(JoinPoint point) {
  14. logger.info("=============before==================");
  15. System.out.println("---------------before---------------");
  16. }
  17. public void after(JoinPoint point, Object retValue) {
  18. logger.info("=============after==================");
  19. System.out.println("---------------after---------------");
  20. }
  21. }

配置文件: spring-service.xml
这里只列举相关的关键配置,其他注解扫描的就没加了

  1. <!-- log 切面类 -->
  2. <bean id="logAspect" class="com.aop.LogAspect" />
  3. <!-- log 的Aop配置 -->
  4. <aop:config proxy-target-class="true">
  5. <aop:aspect ref="logAspect">
  6. <aop:before method="before" pointcut="execution(* com.service..*.*(..))"></aop:before>
  7. <aop:after-returning pointcut="execution(* com.service..*.*(..))" arg-names="point,retValue" returning="retValue" method="after"/>
  8. </aop:aspect>
  9. </aop:config>

测试用例:

  1. @Autowired
  2. @Qualifier("transactionalService")
  3. private ITransactionalService transactionalService;
  4. /**
  5. * 用于测试事物是否提交
  6. *
  7. * @throws Exception
  8. */
  9. @Test
  10. public void testTransactionalCommit() throws Exception {
  11. transactionalService.testQuery();
  12. logger.debug("test---------");
  13. }

上面的配置就是说 通知com.service包下面的类将会被LogAspect切入,before方法表示方法执行之前切入,after方法在方法之后之后切入

处理流程

我们先看下代理中做了些啥事?

  1. 直接debug打到transactionalService.testQuery();看处理的代理是个什么样子的类
    CglibAopProxy.class : 这是一个Cglib代理的类,具体看他的拦截方法

    @Override

    1. public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
    2. Object oldProxy = null;
    3. boolean setProxyContext = false;
    4. Class<?> targetClass = null;
    5. Object target = null;
    6. try {
    7. if (this.advised.exposeProxy) {
    8. // Make invocation available if necessary.
    9. oldProxy = AopContext.setCurrentProxy(proxy);
    10. setProxyContext = true;
    11. }
    12. // May be null. Get as late as possible to minimize the time we
    13. // "own" the target, in case it comes from a pool...
    14. // 这里是获取要执行的目标对象,就是我们的ITransactionalService实现类
    15. target = getTarget();
    16. if (target != null) {
    17. targetClass = target.getClass();
    18. }
    19. // 这里会获得一个拦截链,也就是一系列的advised对象,相当于设计模式中的责任链模式
    20. List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
    21. Object retVal;
    22. // Check whether we only have one InvokerInterceptor: that is,
    23. // no real advice, but just reflective invocation of the target.
    24. if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
    25. // We can skip creating a MethodInvocation: just invoke the target directly.
    26. // Note that the final invoker must be an InvokerInterceptor, so we know
    27. // it does nothing but a reflective operation on the target, and no hot
    28. // swapping or fancy proxying.
    29. retVal = methodProxy.invoke(target, args);
    30. }
    31. else {
    32. // We need to create a method invocation...
    33. // 创造一个方法调用,也就是具体责任链的执行类
    34. // 这个方法里面非常关键,这里执行chain里面的所有代理方法
    35. retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
    36. }
    37. retVal = processReturnType(proxy, target, method, retVal);
    38. return retVal;
    39. }
    40. finally {
    41. if (target != null) {
    42. releaseTarget(target);
    43. }
    44. if (setProxyContext) {
    45. // Restore old proxy.
    46. AopContext.setCurrentProxy(oldProxy);
    47. }
    48. }
    49. }

CglibMethodInvocation类的结构

6370985-69a005b4b9b4b745.png

CglibMethodInvocation类结构

  1. new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();

CglibMethodInvocation的process()方法其实是委托父类去执行的 也就是ReflectiveMethodInvocation

ReflectiveMethodInvocation类
// 这里只列举关键方法,因为上面已经拿到了代理的chain

  1. public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {
  2. // 拦截器列表 里面包装的都是advised
  3. protected final List<?> interceptorsAndDynamicMethodMatchers;
  4. // 计数器
  5. private int currentInterceptorIndex = -1;
  6. @Override
  7. public Object proceed() throws Throwable {
  8. // We start with an index of -1 and increment early.
  9. // 从这里如果大小相等,表示interceptorsAndDynamicMethodMatchers里面的advised已经执行完了.. 就开始执行最终的目标方法
  10. if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
  11. // 执行目标方法
  12. return invokeJoinpoint();
  13. }
  14. // 拿到下一个advised
  15. Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
  16. // 判断是否是InterceptorAndDynamicMethodMatcher这个类型的,这里不用关注
  17. if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
  18. // Evaluate dynamic method matcher here: static part will already have
  19. // been evaluated and found to match.
  20. InterceptorAndDynamicMethodMatcher dm =
  21. (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
  22. if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
  23. return dm.interceptor.invoke(this);
  24. }
  25. else {
  26. // Dynamic matching failed.
  27. // Skip this interceptor and invoke the next in the chain.
  28. return proceed();
  29. }
  30. }
  31. else {
  32. // It's an interceptor, so we just invoke it: The pointcut will have
  33. // been evaluated statically before this object was constructed.
  34. // 执行这个advised,这里可能是AfterReturningAdviceInterceptor可能是MethodBeforeAdviceInterceptor
  35. return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
  36. }
  37. }
  38. }
  39. /**
  40. * Implementation of AOP Alliance MethodInvocation used by this AOP proxy.
  41. */
  42. // 这个类的目的就是为了执行最终的方法而设定的,具体的拦截链路交给了父类的proceed方法处理,只有当父类的proceed方法执行完毕之后,才会回调这个类的invokeJoinpoint方法
  43. private static class CglibMethodInvocation extends ReflectiveMethodInvocation {
  44. private final MethodProxy methodProxy;
  45. private final boolean publicMethod;
  46. public CglibMethodInvocation(Object proxy, Object target, Method method, Object[] arguments,
  47. Class<?> targetClass, List<Object> interceptorsAndDynamicMethodMatchers, MethodProxy methodProxy) {
  48. super(proxy, target, method, arguments, targetClass, interceptorsAndDynamicMethodMatchers);
  49. this.methodProxy = methodProxy;
  50. this.publicMethod = Modifier.isPublic(method.getModifiers());
  51. }
  52. /**
  53. * Gives a marginal performance improvement versus using reflection to
  54. * invoke the target when invoking public methods.
  55. */
  56. @Override
  57. // 最终的执行目标方法
  58. protected Object invokeJoinpoint() throws Throwable {
  59. // 如果执行的目标类的方法是public的,则直接反射调用
  60. if (this.publicMethod) {
  61. return this.methodProxy.invoke(this.target, this.arguments);
  62. }
  63. else {
  64. // 如果执行的目标方法非public的则会交给父类处理
  65. // 父类会调用AopUtils.invokeJoinpointUsingReflection方法
  66. // 其实反射的时候设置了method.setAccessible(true);
  67. return super.invokeJoinpoint();
  68. }
  69. }
  70. }

我们看下具体的advised对象

  • AfterReturningAdviceInterceptor - 目标方法之后执行
  • MethodBeforeAdviceInterceptor - 目标方法执行
    其实这两个方法实现方式是差不多的,都实现了MethodInterceptor接口,只是切入点执行的顺序上做了调整而已

    public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {

    1. private final AfterReturningAdvice advice;
  1. /**
  2. * Create a new AfterReturningAdviceInterceptor for the given advice.
  3. * @param advice the AfterReturningAdvice to wrap
  4. */
  5. public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) {
  6. Assert.notNull(advice, "Advice must not be null");
  7. this.advice = advice;
  8. }
  9. @Override
  10. public Object invoke(MethodInvocation mi) throws Throwable {
  11. // 目标方法,也可以说是责任链对象 因为上面是通过this传递进来的,相当于又执行上面的ReflectiveMethodInvocation的process()方法.去找下一个拦截器这样一个循环
  12. Object retVal = mi.proceed();
  13. // 后置切入点
  14. this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
  15. return retVal;
  16. }
  17. }
  18. public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable {
  19. private MethodBeforeAdvice advice;
  20. /**
  21. * Create a new MethodBeforeAdviceInterceptor for the given advice.
  22. * @param advice the MethodBeforeAdvice to wrap
  23. */
  24. public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
  25. Assert.notNull(advice, "Advice must not be null");
  26. this.advice = advice;
  27. }
  28. @Override
  29. public Object invoke(MethodInvocation mi) throws Throwable {
  30. // 前置切入点执行
  31. this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
  32. // 目标方法执行
  33. return mi.proceed();
  34. }
  35. }

梳理一下:

  1. 通过Cglib代理拿到具体的代理的对象(CglibAopProxy)
  2. 在Cglib中的拦截(intercept)处理中,先获取所有切入点的对象(chain)并且构建了一个责任链类(CglibMethodInvocation),这个责任链类(实际执行过程类:ReflectiveMethodInvocation)包含了所有拦截链(advised集合)对象
  3. 通过这个责任链类开始递归下面所有的拦截类去执行每个advised方法
  4. 执行完所有advised链条方法之后,会到达这个最终的目标方法CglibMethodInvocation.invokeJoinpoint().调用方法这部分都是通过反射去执行的。
  5. 如果被代理的方法不是public类型的则会在反射的时候设置setAccessible为true,破坏了对象封装属性强制调用!

发表评论

表情:
评论列表 (有 0 条评论,269人围观)

还没有评论,来说两句吧...

相关阅读