spring - 不应该建议自调用,但确实如此

标签 spring aspectj spring-aop aop

我在 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/

相关文章:

java - 根据建议的对象调用位置应用方面

java - 无法在 Windows 7 x64 上使用 gradle 构建 spring 框架

javascript - 对 spring @ResourceMapping 方法进行 react ,未使用相同的请求参数调用

json - 基于对象类型的 Spring 集成对象转换器

spring - 你如何忽略 Maven 某些方面的 AspectJ 编译器警告

ide - 详细的 AspectJ 编译器输出

java - 方面按方法注释未执行

java - AspectJ autoproxy 在 GigaSpaces 8 和 Spring 3 中失败,因为类是由不同的类加载器加载的

spring - 类 [org.jongo.bson.RelaxedLazyDBObject] 的对象必须是类 com.mongodb.BasicDBObject 的实例

java - 如何在 AspectJ 中获取 joinPoint.proceed() 结果的参数?