如何使用spring的注解驱动aspectj模式

在使用spring框架的时候,经常会使用到这个tx:annotation-driven来配置自己项目的事务控制,平常我们大部分的时候用的都是默认的模式(不写或者mode="proxy"),proxy是代理模式,仅有外部方法调用才会被代理截获,自身方法调用,即使配置了@Transactional注解,事务也无法生效,也不能应用在非public方法上;而aspectj模式与代理模式不同,aspectj模式可以自身方法调用,也可以应用在非public上。下面来介绍如何使用mode="aspectj"模式

方法/步骤

首先在spring的配置文件中添加<tx:annotation-driven transaction-manager="transactionManager" mode="aspectj"/>mode设置为aspectj模式

 

jvm参数里添加-javaagent:~aspectjweaver-1.8.1.jar

 

如果是tomcat下,也可以添加到catalina.sh中,set JAVA_OPTS中

-javaagent参数添加完成时候,启动服务就可以正常使用aspectj模式了上面说的方法是类加载器织入(Load Time Weaving,LTW),下面再介绍另外一种方法,编译时织入

在pom.xml文件中加入aspectj-maven-plugin插件配置<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.9</version> <configuration> <showWeaveInfo>true</showWeaveInfo> <aspectLibraries> <aspectLibrary> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </aspectLibrary> </aspectLibraries> <source>${java.version}</source> <target>${java.version}</target> <complianceLevel>${java.version}</complianceLevel> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>test-compile</goal> </goals> </execution> </executions></plugin>

 

这几个配置要加上<source>${java.version}</source><target>${java.version}</target><complianceLevel>${java.version}</complianceLevel>否则可能会报以下错误[ERROR] Syntax error, annotations are only available if source level is 1.5 or greater E:\work\datai\code_study\study-master\study-spring-transaction\src\main\java\cn\sw\study\web\controller\UserController.java:12@Controller^^^^^^^^^^[ERROR] Syntax error, annotations are only available if source level is 1.5 or greater E:\work\datai\code_study\study-master\study-spring-transaction\src\main\java\cn\sw\study\web\controller\UserController.java:13@RequestMapping("/user")[ERROR] Missing message: configure.incompatibleComplianceForSource in: org.aspectj.ajdt.ajc.messages <unknown source file>:<no line information>[ERROR] no sources specified <unknown source file>:<no line information>

添加完成之后,maven进行编译,如果出现java:0::0 can't determine annotations of missing type javax.persistence.Entity错误,

 

则需要添加persistence-api依赖<dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0</version> <scope>provided</scope></dependency>

 

编译完成没有错误之后,这个时候不用加-javaagent,再次启动项目,一样可以完成事务织入

注意事项

aspectj有三个时期可以织入,编译器、后编译器、类加载器,有兴趣的可以都试下

猜你喜欢

转载自wddpwzzhao123.iteye.com/blog/2390285