独自快乐|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配置事务首先配置约束
事务本身就需要开启事务以及关闭事务 , 所以可以使用面向切面的思想来对service中的方法进行增强 , spring已经写好了通知 , 所以不需要我们写通知了 , 我们可以通过tx:advice来配置事务通知 , 然后将这个通知织入到service方法中 , 那么此时的service都是被事务增强的方法 , 之后就不需要手动增加事务了 。 配置如下:
推荐阅读
- 快乐棒棒糖|众多男神女神加盟,看看有你期待的人吗,江苏晚会阵容曝光
- 董事长|华熙生物董事长:公司围绕“健康、美丽、快乐事业”不断投入
- 高管|华熙生物董事长:公司围绕“健康、美丽、快乐事业”不断投入
- 何伟|【高管面对面】华熙生物:保留初心 做健康美丽快乐事业
- 可馨说娱乐1|官宣加入恋综,萧亚轩动态轰动了,金莎发文“想体验萧亚轩快乐”
- 过得比我快乐|领土只能远远看着!,世界没有完成统一的3个发达国家
- 白夜追娱1|唯独不见黄明昊引热议,粉丝晒照片打脸黑粉,谢娜晒快乐家族合影
- 小海|原创玖月奇迹王小玮官宣离婚后,独自登上央视舞台,组合已经解散?
- 用智能引领快乐走进新的领域|古代名将能像影视剧游戏中一样挡住乱箭齐发吗?真有一个人能挡住
- 用智能引领快乐走进新的领域|结果悲剧了,网友称厉害了,皇帝竟娶了祖孙两代
