独自快乐|spring框架的入门学习:AOP和面向切面的事务( 十 )

package com.huanfeng.service;public interface AccountService { public void transfer(Integer from,Integer to,Double money);}package com.huanfeng.service;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;import com.huanfeng.dao.AccountDao;public class AccountServiceImpl implements AccountService { private AccountDao ad; private TransactionTemplate tt; public TransactionTemplate getTt() {return tt; } public void setTt(TransactionTemplate tt) {this.tt = tt; } public AccountDao getAd() {return ad; } public void setAd(AccountDao ad) {this.ad = ad; } @Override public void transfer(Integer from, Integer to, Double money) {tt.execute(new TransactionCallbackWithoutResult() {@Overrideprotected void doInTransactionWithoutResult(TransactionStatus arg0) {//减钱ad.decreaseMoney(from, money);//加钱ad.increaseMoney(to, money);}}); }}AccountServiceImpl中需要TransactionTemplate事务模板对象 , 以便于开启事务 , 之后可以测试了:
package com.huanfeng.transaction;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.huanfeng.service.AccountService;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:com/huanfeng/dao/applicationContext3.xml")public class Demo1 { @Resource(name="AccountService") private AccountService as; @Test public void test1() {as.transfer(1, 2, 500d); }}aop配置事务首先配置约束
独自快乐|spring框架的入门学习:AOP和面向切面的事务
独自快乐|spring框架的入门学习:AOP和面向切面的事务
独自快乐|spring框架的入门学习:AOP和面向切面的事务
独自快乐|spring框架的入门学习:AOP和面向切面的事务事务本身就需要开启事务以及关闭事务 , 所以可以使用面向切面的思想来对service中的方法进行增强 , spring已经写好了通知 , 所以不需要我们写通知了 , 我们可以通过tx:advice来配置事务通知 , 然后将这个通知织入到service方法中 , 那么此时的service都是被事务增强的方法 , 之后就不需要手动增加事务了 。 配置如下:


推荐阅读