SpringBoot:事务失效

本文探讨了SpringBoot默认开启事务但可能遇到的不生效问题,包括访问权限限制(仅public方法有效)、异常处理要求、非事务方法、多线程/异步、非Spring容器管理对象以及底层数据库不支持等因素。
摘要由CSDN通过智能技术生成

SpringBoot默认开启事务,也提供了@Transactional帮助我们进行事务管理,使用起来简单方便。不过在实际开发中有时会遇到事务不生效的情况,总结一下,以备不时之需。

1.访问权限控制

Java中有四种访问权限:public、protected、default和private,而@Transactional是通过AOP实现的事务管理,并通过动态代理来调用被事务管理的方法,被代理的方法必须是public修饰的,否者事务不生效。(同理,final、static修饰的方法也不会生效)

protected TransactionAttribute computeTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
    // Don't allow no-public methods as required.
    if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
        return null;
    }

    // The method may be on an interface, but we need attributes from the target class.
    // If the target class is null, the method will be unchanged.
    Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);

    // First try is the method in the target class.
    TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
    if (txAttr != null) {
        return txAttr;
    }

    // Second try is the transaction attribute on the target class.
    txAttr = findTransactionAttribute(specificMethod.getDeclaringClass());
    if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
        return txAttr;
    }

    if (specificMethod != method) {
        // Fallback is to look at the original method.
        txAttr = findTransactionAttribute(method);
        if (txAttr != null) {
            return txAttr;
        }
        // Last fallback is the class of the original method.
        txAttr = findTransactionAttribute(method.getDeclaringClass());
        if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
            return txAttr;
        }
    }

    return null;
}

2.异常未被抛出

SpringBoot中事务回滚需要方法抛出声明的异常,如果方法中捕获了异常或者未抛出声明的异常,事务就不会回滚。

3.方法未被事务管理或事务传播机制选择非事务

4.多线程操作或使用异步操作

5.关闭SpringBoot的事务管理或创建的对象不被Spring容器管理

6.底层数据库不支持事务

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

无敌大盖伦

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

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

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

打赏作者

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

抵扣说明:

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

余额充值