环境说明
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"> <property name="accountDao" ref="accountDao"/> <property name="dataSource" ref="dataSource"/> </bean>
//在applicationContext.xml里面注入 private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } //注入这个数据源 private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void transfer(String outName, String inName, Double money) { //开启事务,创建事务管理器 PlatformTransactionManager ptm = new DataSourceTransactionManager(); //为事务管理器设置与数据层相同的数据源 dstm.setDataSource(dataSource); //事务定义 TransactionDefinition td = new DefaultTransactionDefinition(); //事务状态 TransactionStatus ts = ptm.getTransaction(td); accountDao.inMoney(outName,money); int i = 1/0;//模拟业务层事务过程中出现错误 accountDao.outMoney(inName,money); //提交事务 ptm.commit(ts); }
将业务层的事务处理功能抽取出来制作成AOP通知,利用环绕通知运行期动态织入
public class TxAdvice { //注入dataSource private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public Object transactionManager(ProceedingJoinPoint pjp) throws Throwable { //开启事务 PlatformTransactionManager ptm = new DataSourceTransactionManager(dataSource); //事务定义 TransactionDefinition td = new DefaultTransactionDefinition(); //事务状态 TransactionStatus ts = ptm.getTransaction(td); Object ret = pjp.proceed(pjp.getArgs()); //提交事务 ptm.commit(ts); return ret; } }
在applicationContext.xml配置上面配置AOP通知类,并注入dataSource
<bean id="txAdvice" class="com.yy.aop.TxAdvice"> <property name="dataSource" ref="dataSource"/> </bean>
在applicationContext.xml配置上使用环绕通知将通知类织入到原始业务对象执行过程中
<aop:config> <!-- 配置切入点,切入点表达式--> <aop:pointcut id="pt" expression="execution(* *..transfer(..))"/> <aop:aspect ref="txAdvice"> <aop:around method="transactionManager" pointcut-ref="pt"/> </aop:aspect> </aop:config>