Spring Boot 2.7.5中设置AspectJ事务模式的属性及私有方法事务配置
Spring Boot 2.7.5 私有/自引用方法事务配置指南
一、用属性设置事务模式(无需XML)
Spring Boot支持通过配置属性切换事务管理模式,无需编写XML配置:
- 在
application.properties中添加:
或YAML格式:spring.aop.mode=aspectjspring: aop: mode: aspectj - 同时确保启动类标注
@EnableTransactionManagement,也可直接在该注解中指定模式:@EnableTransactionManagement(mode = AdviceMode.ASPECTJ),两种方式二选一即可。
二、让@Transactional在私有方法生效的额外配置
要实现私有方法和自引用方法的事务增强,还需完成以下配置:
1. 引入AspectJ Weaver依赖
Maven(pom.xml):
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.7</version> <!-- 适配Spring Boot 2.7.5的兼容版本即可 --> </dependency>
Gradle(build.gradle):
implementation 'org.aspectj:aspectjweaver:1.9.7'
2. 启用AspectJ织入
有两种织入方式可选:
方式一:编译时织入(CTW)
编译阶段将事务增强逻辑织入类字节码,适合生产环境:
- Maven配置
aspectj-maven-plugin插件:<build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.14.0</version> <configuration> <complianceLevel>11</complianceLevel> <!-- 匹配你的JDK版本,Spring Boot 2.7.5支持JDK 8-17 --> <aspectLibraries> <aspectLibrary> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </aspectLibrary> </aspectLibraries> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> - Gradle引入
io.freefair.aspectj插件:plugins { id 'io.freefair.aspectj.compile' version '6.5.0' } aspectj { aspectLibraries = [ "org.springframework:spring-aspects" ] }
方式二:加载时织入(LTW)
类加载阶段织入增强逻辑,适合开发调试场景:
- 在
application.properties开启加载时织入:spring.aop.load-time-weaver.enabled=true - 启动应用时添加JVM参数指定代理:
IDE运行可在VM options中配置;Maven运行可在-javaagent:/path/to/aspectjweaver-1.9.7.jarspring-boot:run插件中添加:<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <jvmArguments>-javaagent:${settings.localRepository}/org/aspectj/aspectjweaver/1.9.7/aspectjweaver-1.9.7.jar</jvmArguments> </configuration> </plugin>
3. 注意事项
- 私有方法的
@Transactional必须直接标注在目标方法上,无法通过继承或接口传递。 - 自引用方法的事务在AspectJ模式下自动生效,无需通过
AopContext.currentProxy()获取代理对象。
内容的提问来源于stack exchange,提问作者dermoritz
相关产品推荐
相关产品推荐

