本地事务系列之四:使用AOP

阅读更多
Spring AOP通过在文件中配置来管理事务,好处是对代码侵入性小。

Spring AOP使用AspectJ表达式来定义切点,所以pom文件加入:

    org.aspectj
    aspectjweaver
    1.7.0



FruitShop实现:

方法中除了使用继承自JdbcDaoSupport的JdbcTemplate来操作数据库外,没有其它与事务有关的代码:

public class AopTxFruitShop extends JdbcDaoSupport implements FruitShop {

	@Override
	public boolean purchase(int fruitId, String userName, int count) {
		String querySql = "SELECT PRICE FROM FRUIT WHERE ID = ?";
		String upStockSql = "UPDATE FRUIT_STOCK SET STOCK = STOCK - ? WHERE ID = ?";
		String upAccountSql = "UPDATE ACCOUNT SET BALANCE = BALANCE - ? WHERE USERNAME = ?";

		int price = getJdbcTemplate().queryForInt(querySql, new Object[] { fruitId });
		getJdbcTemplate().update(upStockSql, new Object[] { count, fruitId });
		getJdbcTemplate().update(upAccountSql, new Object[] { price * count, userName });
		return true;
	}
}


beans-fruitshop-aop.xml文件:



  
  
  	
  		
	
  
  
  
  	
	
  

  
  	
	
	
	
  
  
  
  	
  
  
  
  	
  



测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/beans-fruitshop-aop.xml" })
public class AopTxFruitShopTest {

	@Resource(name = "aopTxFruitShop")
	FruitShop aopTxFruitShop;
	
	@Test
	public void test() {
		int fruitId = 1;
		String userName = "user1";
		int count = 3;
		aopTxFruitShop.purchase(fruitId, userName, count);
	}
}

你可能感兴趣的:(spring,jdbc,transaction)