注解 @Transactional 事务类内调用不生效问题及解决办法

在 Spring 的 AOP 代理下,只有目标方法由外部调用,目标方法才由 Spring 生成的代理对象来管理,这会造成自调用问题。

若同一类中的其他没有@Transactional 注解的方法内部调用有@Transactional 注解的方法,有@Transactional 注解的方法的事务被忽略,不会发生回滚

如上代码,在方法test2()中抛出异常时,数据操作不会回滚

解决方案

思路: 强制使用 AspectJ 对方法进行切面

Springboot 引入 AspectJ 切面

pom.xml 中添加AspectJ:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</version>
</dependency>

启动类中添加 @EnableAspectJAutoProxy(exposeProxy = true)

注意: exposeProxy = true 若不添加,则会报:

java.lang.IllegalStateException:

Cannot find current proxy: Set ‘exposeProxy’ property on Advised to ‘true’ to make it available,

and ensure that AopContext.currentProxy() is invoked in the same thread as the AOP invocation context.

修改为如下代码,事务就生效啦

((T) AopContext.currentProxy())

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值