有这么一个类:

@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---");
}
}