TransactionTemplate继承于TransactionOperations和InitializingBean这两个接口。其中InitializingBean接口中的afterPropertiesSet方法,Spring Bean初始化完成后执行,TransactionTemplate用来检查事务管理器是否已经初始化完毕,如下所示。
@Override
public void afterPropertiesSet() {
if (this.transactionManager == null) {
throw new IllegalArgumentException("Property 'transactionManager' is required");
}
}
继承于TransactionOperations的execute方法是事务执行的核心方法,事务执行分成三个步骤:
- 获取事务连接;
- 执行目标方法;
- 提交或者回滚事务;
```java
public
T execute(TransactionCallback action) throws TransactionException {
}if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
}
else {
//1.获取事务连接
TransactionStatus status = this.transactionManager.getTransaction(this);
T result;
try {
//2.执行业务方法
result = action.doInTransaction(status);
}
catch (RuntimeException ex) {
// Transactional code threw application exception -> rollback
rollbackOnException(status, ex);
throw ex;
}
catch (Error err) {
// Transactional code threw error -> rollback
rollbackOnException(status, err);
throw err;
}
catch (Throwable ex) {
// Transactional code threw unexpected exception -> rollback
rollbackOnException(status, ex);
throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");
}
//3.提交事务
this.transactionManager.commit(status);
return result;
}
```