我在 Spring AOP AspectJ 中遇到了一个奇怪的行为:不应该建议自调用,但在我的应用程序中确实如此。来自 Spring documentation :
However, once the call has finally reached the target object, the SimplePojo reference in this case, any method calls that it may make on itself, such as this.bar() or this.foo(), are going to be invoked against the this reference, and not the proxy. This has important implications. It means that self-invocation is not going to result in the advice associated with a method invocation getting a chance to execute.
但在我的简单应用程序中,由以下内容组成:
测试方面
@Aspect
@Component
public class TestAspect {
private static final Logger logger = LoggerFactory.getLogger(TestAspect.class);
@Pointcut("execution(* org.mypackage.TestService.method(..))")
public void participateAroundPointcut(){}
@Around("participateAroundPointcut()")
public void testAround(ProceedingJoinPoint joinPoint) throws Throwable{
logger.debug("Pre-execution;");
joinPoint.proceed();
logger.debug("Post-execution");
}
}
测试服务:
@Service
public class TestService {
private static final Logger logger = LoggerFactory.getLogger(TestService.class);
public void method(){
logger.debug("Executing method();");
}
public void service(){
logger.debug("Executing service();");
this.method();
}
}
和配置文件:
<context:component-scan base-package="org.mypackage" />
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="testAspect" class="org.mypackage.aop.aspects.TestAspect" factory-method="aspectOf"/>
我得到了自调用建议:
DEBUG: org.mypackage.TestService - Executing service();
DEBUG: org.mypackage.aop.aspects.TestAspect - Pre-execution;
DEBUG: org.mypackage.TestService - Executing method();
DEBUG: org.mypackage.aop.aspects.TestAspect - Post-execution
我不明白为什么会发生这种情况。
最佳答案
问题很可能是 IDE - 如果您使用 Eclipse 并为您的项目启用了 AspectJ,AspectJ 插件将编织您的目标类。尝试在 IDE 之外运行测试(如果是 Maven 项目,可以运行 mvn clean test
),然后您应该会看到预期的行为
关于spring - 不应该建议自调用,但确实如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14520091/