TransactionTemplate继承于TransactionOperations和InitializingBean这两个接口。其中InitializingBean接口中的afterPropertiesSet方法,Spring Bean初始化完成后执行,TransactionTemplate用来检查事务管理器是否已经初始化完毕,如下所示。

  1. @Override
  2. public void afterPropertiesSet() {
  3. if (this.transactionManager == null) {
  4. throw new IllegalArgumentException("Property 'transactionManager' is required");
  5. }
  6. }

继承于TransactionOperations的execute方法是事务执行的核心方法,事务执行分成三个步骤:

  • 获取事务连接;
  • 执行目标方法;
  • 提交或者回滚事务; ```java public T execute(TransactionCallback action) throws TransactionException {
    1. if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
    2. return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
    3. }
    4. else {
    5. //1.获取事务连接
    6. TransactionStatus status = this.transactionManager.getTransaction(this);
    7. T result;
    8. try {
    9. //2.执行业务方法
    10. result = action.doInTransaction(status);
    11. }
    12. catch (RuntimeException ex) {
    13. // Transactional code threw application exception -> rollback
    14. rollbackOnException(status, ex);
    15. throw ex;
    16. }
    17. catch (Error err) {
    18. // Transactional code threw error -> rollback
    19. rollbackOnException(status, err);
    20. throw err;
    21. }
    22. catch (Throwable ex) {
    23. // Transactional code threw unexpected exception -> rollback
    24. rollbackOnException(status, ex);
    25. throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");
    26. }
    27. //3.提交事务
    28. this.transactionManager.commit(status);
    29. return result;
    30. }
    }

```

参考

https://www.cnblogs.com/dennyzhangdd/p/9602673.html