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