同一个类中方法调用,导致@Transactional失效

1.背景

查了一下Spring文档,就是上面这段话所说的情况。

2.Spring官方文档有这么一段话

https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction-declarative

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation (in effect, a method within the target object calling another method of the target object) does not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional. Also, the proxy must be fully initialized to provide the expected behavior, so you should not rely on this feature in your initialization code — for example, in a @PostConstruct method.

我有一个Service类,

有一个方法会被当前类之外的类调用,称之为“A方法”,

A方法调用同一个类的另一个方法,称之为“B方法”,@Transactional注解加在B方法上面,

再来看官方文档的这句话,only external method calls coming in through the proxy are intercepted. 在这个例子中,A方法和B方法属于同一个类,同一个类的两个方法之间的调用,并没有“coming in through the proxy”,没有穿过Spring的动态代理。这样就根本没有形成Spring事务。

另外一个类的方法调用A方法,跨越了两个类,这样才是穿过了Spring的动态代理。

因此这里必须把@Transactional注解写在A方法上面。我这样修改了之后,事务就会回滚了,验证了Spring官方文档的这段话是正确的。

  • 24
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值