看下它的核心代码:
@Override public <T> T execute(TransactionCallback<T> action) throws TransactionException { if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) { return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action); } else { TransactionStatus status = this.transactionManager.getTransaction(this); T result; try { 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 (Exception 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; } }
需要执行事务的业务逻辑被封装成action,它所做的也很简单,在action执行前后进行事务的开启和提交(或着rollback)。开启事务时需要transactionManager的getTransaction方法获取TransactionStatus,而这个方法的参数是TransactionDefinition,前面说过TransactionTemplate本身就是TransactionDefinition的实现,所以将this作为参数传递给这个方法就可以。
也可以看到,TransactionTemplate和基于AOP的配置一样,也是在方法前后执行事务的开启和提交,只是实现的方式改变了。
基于 Spring 设计并实现 RESTful Web Services
Spring-3.2.4 + Quartz-2.2.0集成实例