社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
前面博客说到xml方式实现声明式事务管理,这回来说下注解方式的声明式事务管理。
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd ">
</beans>
public interface AccountService {
//转账方法
void transfer(Integer from,Integer to,Double money);
}
/****************************************************/
public class AccountServiceImpl implements AccountService {
private AccountDao ad;
public void setAd(AccountDao ad) {
this.ad = ad;
}
@Override
//转账方法
public void transfer( Integer from, Integer to, Double money){
//减钱
ad.decreaseMoney(from, money);
//异常代码
int i = 1/0;
//加钱
ad.increaseMoney(to, money);
}
}
<!-- 开启注解管理事务 -->
<tx:annotation-driven/>
在使用事务的类或者方法上加一个注解:@Transactional
@Override
//转账方法
@Transactional(isolation =Isolation.REPEATABLE_READ,propagation= Propagation.REQUIRED,readOnly= false)
public void transfer( Integer from, Integer to, Double money){
//减钱
ad.decreaseMoney(from, money);
int i = 1/0;
//加钱
ad.increaseMoney(to, money);
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext2.xml")
public class Demo2 {
@Resource(name = "accountService")
private AccountService as;
@Test
public void fun1(){
as.transfer(1, 2, 100d);
}
结果: A和B账户的钱都没有发生变化,事务注解成功!
上面这种是AspectJ的方式,Aspect 是一套独立的面向切面编程的解决方案。Spring 集成了与Aspect 5 一样的注解,并使用了AspectJ 来做切入点的解析和匹配。
以上介绍了AOP注解方式实现声明式事务,相对于XML方式,代码简洁了,注解方式越来越流行,感谢您的阅读!
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!