Spring AOP之源码分析

  在研究@Enable*注解的应用之:声明式事务@EnableTransactionManagement详解源码时,配置中context装置了一个TransactionInterceptor的bean。对这个类比较好奇因为Interceptor,因为MyBatis功能点之二(1):MyBatis提供的拦截器平台中也分析过interceptor的使用,这个Spring Interceptor是怎样成体系工作的呢?    

      

  从图上可以观察到Advice接口,所以这是Spring AOP实现的增强通知部分。下面从TransactionInterceptor开始倒推逻辑分析Spring AOP的架构:

  1、TransactionInterceptor的加载:

      在@Enable*注解的应用之:声明式事务@EnableTransactionManagement详解中有明确结论——ProxyTransactionManagementConfiguration中Java Bean的方式置于context中。

  2、观察下图:典型的对应aop配置中的相关内容。

            

    MethodInvocation与MethodInterceptor实现类相互依赖:

      ReflectiveMethodInvocation使用TransactionInterceptor中的invoke方法,ReflectiveMethodInvocation自己作为invoke方法的参数;

      TransactionInterceptor调用TransactionAspectSupport中的 invokeWithinTransaction方法,参数是ReflectiveMethodInvocation.getMethod——被代理对象,targetclass——代理对象。

    事务处理逻辑封装在invokeWithinTransaction方法中。

  3、在Spring核心思想之 AOP:在自定义容器基础上实现AOP功能实现了功能简单的aop,了解aop的执行在beanpostProcessor中。下面验证下上述事务功能是不是在某个后置处理中调用,确定是哪个后置处理器。

            

  阅读上图中代码可以知道遍历对当前bean,遍历使用processor。通过调试,可知是InfrastructureAdvisorAutoProxyCreator

            

  其类图如下:

            

   在其父类AbstractAutoProxyCreator方法wrapIfNecessary中进行实际aop代理的处理:

            

posted on 2024-03-19 19:28  池塘里洗澡的鸭子  阅读(1)  评论(0编辑  收藏  举报