1、在spring配置文件中添加 <aop:aspectj-autoproxy expose-proxy="true" proxy-target-class="true" />声明自动代理
<!-- 标识通过aop框架暴露该代理,aopContext能够访问. -->
proxy-target-class="false" 默认为false,表示使用jdk的动态代理,
proxy-target-class="true" 为true时,表示使用CGLib动态代理技术来实现增强处理。
spring配置xml文件需配套使用名空间:
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
2、springboot
2-1.引入maven依赖即可生效
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2-2.但是要想默认将代理暴露在aop中,个别情况可能还需要@EnableAspectJAutoProxy的帮助,exposeProxy和proxyTargetClass含义同上
3、AopContext.currentProxy()来获取代理类
4、使用代理类proxy进行代理调用内部声明了事务的方法
5、代码简单示例如下
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by ysma on 2019/4/25.
*/
@Service
public class TransactionService {
public void methodA(){
boolean flag = true;
if(flag){
TransactionService proxy = (TransactionService)AopContext.currentProxy();
proxy.methodB();//生效
} else {
methodB();//事务不生效
}
}
@Transactional
public void methodB(){
//my transaction
}
}