在同一个类中调用另一个方法没有触发 Spring AOP 的问题
原创
©著作权归作者所有:来自51CTO博客作者happywzy的原创作品,请联系作者获取转载授权,否则将追究法律责任
有这么一个类:
@Service
@Sl4j
public class SomeService {
public void hello(String someParam) {
log.info("---SomeService: hello invoked, param: {}---", someParam);
test();
}
public void test() {
log.info("---SomeService: test invoked---");
}
}
有这么一个AOP
// 定义切点
@Pointcut(value = "execution(public * com.test.SomeService.test())")
private void activeAspect() {
}
@AfterReturning(value = "activeAspect()")
private void activeSuccess(JoinPoint joinPoint) {
// todo 业务处理
System.out.println("test");
}
我们的计划是通过定义切点,处理SomeService.test()
返回之后的业务逻辑,但是实际情况是这个AOP
一直不生效。
原因是test()
方法不是直接被调用的,而是通过SomeService.hello()
方法间接被调用的。
Spring AOP 是使用了一个代理对象来包装目标对象, 并拦截目标对象的方法调用。在目标对象中调用自己类内部实现的方法时, 这些调用并不会转发到代理对象中, 甚至代理对象都不知道有此调用的存在。
解决办法:
@Service
@Sl4j
public class SomeService {
@Autowired
private SomeService self;
public void hello(String someParam) {
log.info("---SomeService: hello invoked, param: {}---", someParam);
self.test();
}
public void test() {
log.info("---SomeService: test invoked---");
}
}