spring事務管理源碼解析之@EnableTransactionManagement

說在前面spring

本文轉自「天河聊技術」微信公衆號微信

@EnableTransactionManagement的做用和<tx:annotation-driven/>做用同樣this

 

正文代理

源碼解析事務

先看下這個註解@EnableTransactionManagement的內容get

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {

默認是jdk動態代理源碼

boolean proxyTargetClass() default false;
AdviceMode mode() default AdviceMode.PROXY;

 

這個註解的基於proxy模式解析類是org.springframework.transaction.annotation.ProxyTransactionManagementConfigurationit

@Configuration
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {

   @Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
   @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
   public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
//    建立BeanFactoryTransactionAttributeSourceAdvisor
      BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
//    設置transactionAttributeSource
      advisor.setTransactionAttributeSource(transactionAttributeSource());
//    設置事務攔截器
      advisor.setAdvice(transactionInterceptor());
      if (this.enableTx != null) {
         advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
      }
      return advisor;
   }

   @Bean
   @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
   public TransactionAttributeSource transactionAttributeSource() {
      return new AnnotationTransactionAttributeSource();
   }

   @Bean
   @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
   public TransactionInterceptor transactionInterceptor() {
//    建立事務攔截器
      TransactionInterceptor interceptor = new TransactionInterceptor();
//    設置transactionAttributeSource
      interceptor.setTransactionAttributeSource(transactionAttributeSource());
      if (this.txManager != null) {
//       設置事務管理器
         interceptor.setTransactionManager(this.txManager);
      }
      return interceptor;
   }

 

基於aspectj模式的解析類是org.springframework.transaction.aspectj.AspectJTransactionManagementConfigurationio

@Configuration
public class AspectJTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {

   @Bean(name = TransactionManagementConfigUtils.TRANSACTION_ASPECT_BEAN_NAME)
   @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
   public AnnotationTransactionAspect transactionAspect() {
//    建立事務註解切面
      AnnotationTransactionAspect txAspect = AnnotationTransactionAspect.aspectOf();
//    設置事務管理器
      if (this.txManager != null) {
         txAspect.setTransactionManager(this.txManager);
      }
      return txAspect;
   }

 

說到最後class

本次解析僅表明我的看法,僅供參考。

相關文章
相關標籤/搜索