不应该建议自我调用,但确实如此 [英] Self-invocation shouldn't be adviced but it does

查看:19
本文介绍了不应该建议自我调用,但确实如此的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 Spring AOP AspectJ 有一个奇怪的行为:不应该建议自我调用,但在我的应用程序中它确实如此.来自 Spring 文档:

I'm getting a weird behavior by Spring AOP AspectJ: self-invocation shouldn't be adviced, but in my application it does. From Spring documentation:

然而,一旦调用最终到达目标对象,在这种情况下,SimplePojo 引用,它可能进行的任何方法调用本身,例如 this.bar() 或 this.foo(),将被调用针对 this 引用,而不是代理.这有重要的影响.这意味着自调用不会导致与方法调用相关的建议有机会执行.

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.

但在我的简单应用程序中,由:

But in my simple application, composed by:

一个测试方面

@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"/>

我得到了自我调用的建议:

I get the self-invocation adviced:

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

我不明白为什么会这样.

I can't figure out why this happens.

推荐答案

您的配置使用 AspectJ 实现.

Your configuration uses AspectJ implementation.

它被配置为: .(官方文档)

proxy-target-class="true" 仅表示将使用 CGLIB 代理而不是 Java 动态代理.

proxy-target-class="true" only says that CGLIB proxies will be used instead of Java Dynamic Proxies.

我猜你想用 CGLIB 代理配置 Spring AOP.在这种情况下,配置字符串如下所示:

I guess you want to configure Spring AOP with CGLIB proxies. In that case the config string looks like:

<aop:config proxy-target-class="true">
...
</aop:config>

这篇关于不应该建议自我调用,但确实如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆