自定义注解+Aop实现spring声明式事务

SpringAop+自定义注解实现声明式事务

Spring事务实现方式
@Override
@Transactional
public Integer insertUser() {
    int i = userMapper.insertUser();
    int j = 1/0;
    return i;
}

spring中使用@Transactional来控制,当发生异常时,回滚当前所有事务。

这个注解是如何实现的呢?

先自定义一个注解

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTransactional {
}

利用Aop的around去生效这个注解

@Aspect
@Component
public class MyTransactionalAop {

    @Autowired
    private TransactionaUtil transactionaUtil;

    @Around(value = "@annotation(com.example.annotation.MyTransactional)")
    public Object around(ProceedingJoinPoint joinPoint){
        TransactionStatus begin = null;
        try{
            begin = transactionaUtil.begin();
            Object result = joinPoint.proceed();
            transactionaUtil.commit(begin);
            return result;
        } catch (Throwable throwable) {
            if(begin!=null){
                transactionaUtil.rollback(begin);
            }
            throwable.printStackTrace();
            return 0;
        }
    }

}

使用的时候

@MyTransactional
    public Integer insertUser() throws RuntimeException {
    int i = userMapper.insertUser();
    int j = 1/0;
    return i;
}

这样就实现了自定义注解的事务异常回滚机制

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原味的你

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值