上一篇文章提到Spring @Transactional 坑点中的前两个坑点都是用比较常规的方法解决的,spring官方提到过aspectj这种解决方案,随后我花时间研究了一下确实解决了,大概步骤是这样的:
1、pom.xml中加maven依赖:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.4</version>
</dependency>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.8</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<target>1.8</target>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
2、IDEA安装AspectJ插件,确保这两个插件安装并启用(据说只有旗舰版才支持)
3、设置java compiler,需要点击 Apply,如下图:
4、配置类上配置@EnableTransactionManagement(mode = AdviceMode.ASPECTJ),以spring boot应用为例:
5、启动spring boot应用,查看效果:
从上图中可以看出,确实解决了事务不生效的问题,至于原理,我暂时也没有研究过,只能感叹字节码技术的强大之处。