`
darrenzhu
  • 浏览: 782417 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Spring注解事物@Transactional不工作

阅读更多
“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, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.

在默认的代理模式下,只有目标方法由外部调用,才能被 Spring 的事务拦截器拦截。在同一个类中的两个方法直接调用,是不会被 Spring 的事务拦截器拦截,就像上面的 save 方法直接调用了同一个类中的 method1方法,method1 方法不会被 Spring 的事务拦截器拦截。可以使用 AspectJ 取代 Spring AOP 代理来解决这个问题,但是这里暂不讨论。”

以上内容来自链接:

Spring Boot 中使用 @Transactional 注解配置事务管理
https://blog.csdn.net/nextyu/article/details/78669997

以上内容肉测发现确实是这个问题,刚开始事物方法定义为私有的,当然不行,后面以为是抛出的异常不是RuntimeException,但是事实上Spring已经封装了一层,所以其实所有的异常经过Spring重新抛出后就已经是RuntimeExeption的了,最后才发现是因为同一个类的方法A调用事物方法B的问题,将事物方法B放到单独的类,然后方法A再调用方法B,事物生效。

另外需要明确几点:

默认配置下 Spring 只会回滚运行时、未检查异常(继承自 RuntimeException 的异常)或者 Error。参考这里
@Transactional 注解只能应用到 public 方法才有效。


对于自调用获同一个类中调用的解决方案:
1)放到单独的类中变成外部调用
2)获取对应的代理类,调代理类上的同名方法

a)配置
@EnableAspectJAutoProxy(exposeProxy=true)
public class Bootstrap {
}

b)调用方式
int[] effectedRows = ((SkuBasicCreationServiceImpl)AopContext.currentProxy()).createSkuWithTransaction(skuCreationDO, skuBarCodeDOs, skuMUnitDOs, skuTaxClsDO);


事务注解Transactional在同一个类中调用的失效问题
[url]https://blog.csdn.net/ligeforrent/article/details/79996797[/url]


spring @transactional public和自调用方法的问题处理
https://blog.csdn.net/zy_281870667/article/details/77164312

springboot的注解@EnableAspectJAutoProxy讲解
https://blog.csdn.net/pml18710973036/article/details/61654277

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics