在 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())