56、Spring5.x源码之旅五十七事务注解EnableTransactionManagement

深入解析Spring框架中@EnableTransactionManagement注解的源码实现,包括TransactionManagementConfigurationSelector、AutoProxyRegistrar、ProxyTransactionManagementConfiguration等核心组件的初始化流程与AOP代理机制,帮助你彻底理解Spring事务管理的底层原理。

  • 初始化流程图
  • @EnableTransactionManagement做了什么
    • TransactionManagementConfigurationSelector
    • AdviceModeImportSelector的selectImports
    • TransactionManagementConfigurationSelector的selectImports
    • AutoProxyRegistrar注册AOP处理器
      • registerBeanDefinitions
    • ProxyTransactionManagementConfiguration代理事务配置
      • BeanFactoryTransactionAttributeSourceAdvisor事务属性通知器
      • TransactionAttributeSource事务属性源
      • TransactionInterceptor事务拦截器
      • TransactionalEventListenerFactory事务事件监听工厂

初始化流程图

 

@EnableTransactionManagement做了什么

我们新来看下这个注解吧,可以看到他也有代理方式proxyTargetClass,默认falseJDK动态代理,还有AdviceMode,这个就是后面创建那种类型的Advice,默认是代理,这个后面会有看到,其实这个跟AOP注解的类似,也会import一个类TransactionManagementConfigurationSelector

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {
   
     
	boolean proxyTargetClass() default false;
	AdviceMode mode() default AdviceMode.PROXY;
	int order() default Ordered.LOWEST_PRECEDENCE;

}

TransactionManagementConfigurationSelector

这个AdviceModeImportSelector是实现了ImportSelector,我们前面讲过,这个是可以import类名数组的。
 

AdviceModeImportSelector的selectImports

主要是获取属性,然后传给TransactionManagementConfigurationSelectorselectImports
 

TransactionManagementConfigurationSelector的selectImports

这里就是AdviceMode的用处啦,默认是用代理,另外一个就是ASPECTJ,我们主要讲代理。
 

AutoProxyRegistrar注册AOP处理器

这个类型前面讲过,解析到的时候会被实例化,加载bean定义的时候调用registerBeanDefinitions方法。
 

registerBeanDefinitions

会注册AOP处理器InfrastructureAdvisorAutoProxyCreator
 
 

ProxyTransactionManagementConfiguration代理事务配置

主要是注册事务需要用的一些类,而且Role=ROLE_INFRASTRUCTURE都是属于内部级别的。

BeanFactoryTransactionAttributeSourceAdvisor事务属性通知器

里面存放事务注解的方法相关的属性。
 

TransactionAttributeSource事务属性源

就是事务注解的一些属性,也用来解析事务注解属性。
 

TransactionInterceptor事务拦截器

事务的方法拦截器,实现了方法拦截器MethodInterceptor
 

TransactionalEventListenerFactory事务事件监听工厂

可以为特定的方法创建事务事件监听器,实现了EventListenerFactory接口。
 

基本就这些东西,后面看他们是怎么作用的吧。

好了,今天就到这里了,希望对学习理解有帮助,大神看见勿喷,仅为自己的学习理解,能力有限,请多包涵。