Loading

TransactionTemplate的工作原理

1 初始化

DataSourceTransactionManagerAutoConfiguration.JdbcTransactionManagerConfiguration#transactionManager()会创建transactionManagerbean对象:

@Bean  
@ConditionalOnMissingBean(TransactionManager.class)  
DataSourceTransactionManager transactionManager(Environment environment, DataSource dataSource,  
      ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {  
   DataSourceTransactionManager transactionManager = createTransactionManager(environment, dataSource);  
   transactionManagerCustomizers.ifAvailable((customizers) -> customizers.customize(transactionManager));  
   return transactionManager;  
}

它会创建JdbcTransactionManagerDataSourceTransactionManager实现类:

private DataSourceTransactionManager createTransactionManager(Environment environment, DataSource dataSource) {  
   return environment.getProperty("spring.dao.exceptiontranslation.enabled", Boolean.class, Boolean.TRUE)  
         ? new JdbcTransactionManager(dataSource) : new DataSourceTransactionManager(dataSource);  
}

TransactionAutoConfiguration.TransactionTemplateConfiguration#transactionTemplate()会创建transactionTemplatebean对象,将上述transactionManager注入:

@Bean  
@ConditionalOnMissingBean(TransactionOperations.class)  
public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {  
   return new TransactionTemplate(transactionManager);  
}

2 事务管理流程

通过TransactionTemplate#execute()方法可以进行编程式事务管理,其内部会调用transactionManager进行获取事务、提交事务和回滚事务:

public <T> T execute(TransactionCallback<T> action) throws TransactionException {  
   Assert.state(this.transactionManager != null, "No PlatformTransactionManager set");  
  
   if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {  
      // WebSphereUowTransactionManager事务管理流程
      return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);  
   }  
   else {  
      // 获取事务
      TransactionStatus status = this.transactionManager.getTransaction(this);  
      T result;  
      try {  
         // 执行业务方法
         result = action.doInTransaction(status);  
      }  
      // 回滚事务:RuntimeException/Error/Throwable异常才会回滚
      catch (RuntimeException | Error ex) {  
         rollbackOnException(status, ex);  
         throw ex;  
      }  
      catch (Throwable ex) {  
         // Transactional code threw unexpected exception -> rollback  
         rollbackOnException(status, ex);  
         throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");  
      }  
      // 提交事务
      this.transactionManager.commit(status);  
      return result;  
   }  
}
posted @ 2023-01-09 21:03  Xianuii  阅读(722)  评论(0编辑  收藏  举报