您当前的位置: 首页 >  spring

杨林伟

暂无认证

  • 3浏览

    0关注

    3337博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

13Spring - Spring转账Demo(了解事务及AOP)

杨林伟 发布时间:2019-04-03 10:22:19 ,浏览量:3

Spring的转账案例 1)代码准备

1)创建业务层


public interface AccountService {
    public void transfer(String from, String to, Double money);
}

-----------------------------------------------------------------------------------

public class AccountServiceImpl implements AccountService {
    // 业务层注入 DAO:
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    /**
     * from:转出的账号
     * to:转入的账号
     * money:转账金额
     */
    public void transfer(String from, String to, Double money) {
        accountDao.outMoney(from, money);
        accountDao.inMoney(to, money);
    }
}

2)创建DAO类


public interface AccountDao {

    public void outMoney(String from, Double money);

    public void inMoney(String to, Double money);
}

-------------------------------------------------------------------------------

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    @Override
    public void outMoney(String from, Double money) {
        this.getJdbcTemplate().update("update account set money = money - ? where
                name = ? ", money,from);
    }

    @Override
    public void inMoney(String to, Double money) {
        this.getJdbcTemplate().update("update account set money = money + ? where
                name = ? ", money,to);
    }
}

3)配置业务层和DAO类



		




		

3)测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext2.xml")
public class SpringDemo4 {
    @Resource(name = "accountService")
    private AccountService accountService;

    @Test
    // 转账的测试:
    public void demo1() {
        accountService.transfer("会希", "凤姐", 1000d);
    }
}
第一种 - Spring的编程式事务

1)配置事务管理器


		

2)配置事务管理模板


		

3)业务层注入事务管理模板



	
	
	
	
	

4)代码实现

 public void transfer(final String from, final String to, final Double money) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                accountDao.outMoney(from, money);
                int d = 1 / 0;
                accountDao.inMoney(to, money);
            }
        });
    }
第二种 - Spring的声明式事务AOP(XML的方式)

1)配置事务管理器


		

2)配置事务通知




		
		


3)配置AOP事务


	
	

第二种 - Spring的声明式事务AOP(注解的方式)

1)配置事务管理器


		

2)开启事务管理的注解


3)在使用事务的类上添加一个注解:@Transactional 在这里插入图片描述

关注
打赏
1662376985
查看更多评论
立即登录/注册

微信扫码登录

0.0600s