注意:如果想要理解spring 的声明式事务,必须先理解AOP 的原理。
一、spring注册 InfrastructureAdvisorAutoProxyCreator
- 通过
@EnableTransactionManagement 可以看到先把TransactionManagementConfigurationSelector通过@Import注册到spring。同时注意,mode 的默认值是PROXY

-
TransactionManagementConfigurationSelector间接 实现了 ImportSelector 接口,所以就有了将某个bean引入spring 的能力。会把 AutoProxyRegistrar 和 ProxyTransactionManagementConfiguration 引入到spring

-
AutoProxyRegistrar 实现了
ImportBeanDefinitionRegistrar,所以会用registry将bean注入到spring中。此处还是使用PROXY模式下的逻辑
-
最终
registry会将 InfrastructureAdvisorAutoProxyCreator 以org.springframework.aop.config.internalAutoProxyCreator为name注入到spring中。InfrastructureAdvisorAutoProxyCreator 和AOP 的AnnotationAwareAspectJAutoProxyCreator.class一样,也实现了 BeanPostProcessor接口,成为了spring 的 BeanPostProcessor后置处理器

二、特别注意
- 此处把
InfrastructureAdvisorAutoProxyCreator以 org.springframework.aop.config.internalAutoProxyCreator为name注入到spring中。和 AOP 把 AnnotationAwareAspectJAutoProxyCreator.class注入到spring使用的BeanName是一样的。下面的两个调用会进入到同一个方法中。那么如果一个方法即使用 声明式事务、又使用 AOP 会如何?

- 在初始化这个类的时候就会定义好优先级。AOP的 AnnotationAwareAspectJAutoProxyCreator优先级最高,声明式事务 的 InfrastructureAdvisorAutoProxyCreator优先级最低。

- 具体的体现。如果一个方法即使用 声明式事务、又使用 AOP 。那么会使用AOP 的AnnotationAwareAspectJAutoProxyCreator.class,在AOP的后置处理器处理连接链

三、InfrastructureAdvisorAutoProxyCreator分析

InfrastructureAdvisorAutoProxyCreator 是间接实现了 BeanPostProcessor接口。
四、获取代理对象
与AOP 获取代理对象是一样的。
五、ProxyTransactionManagementConfiguration 分析
在一、2 中,除了往spring注册 AutoProxyRegistrar 还往spring中注册了 ProxyTransactionManagementConfiguration。

transactionAttributeSource()主要是用来解析事务注解的属性


transactionInterceptor(TransactionAttributeSource transactionAttributeSource)方法用来设置 动态代理时候的连接链,并把TransactionManager事务管理器设置进去,到时好做 commit 或者 rollback
六、代理链
声明式事务的代理链只有一个链,所以没啥好分析的。与AOP的代理链一起分析更带劲。
在 二、特别注意中可知,如果一个方法即使用 声明式事务、又使用 AOP,那么最终会使用AOP的后置处理器。所以说最后的代理对象,也是使用同一个代理对象。所以说当调用 目标方法时进入到invoke 方法后可以看到拦截链。

很明显声明式事务 和AOP 的拦截链是混在一起的。而且是排在第一位的

七、声明式事务的代理链
框中的方法,其实 是在 各自的方法中调用 TransactionManager().commit 、 TransactionManager().rollback 等方法。与编程式事务无异。所以说声明式事务的底层是编程式事务

八、AOP 与 声明式事务 的调用过程

九、AOP 与 声明式事务 的调用逻辑

转载:https://blog.csdn.net/langwuzhe/article/details/128782839