不应该建议自我调用,但是应该这样做 [英] Self-invocation shouldn't be adviced but it does

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

问题描述

Spring AOP AspectJ出现了一种奇怪的行为:不应建议自我调用,但在我的应用程序中会建议这样做.来自春季文档:

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(),将被调用 反对此参考,而不是代理.这很重要 含义. 这意味着自调用不会导致 与方法调用相关的建议有机会 执行.

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:

TestAspect

a TestAspect

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

}

TestService:

a TestService:

@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

我不知道为什么会这样.

I can't figure out why this happens.

推荐答案

您的配置使用AspectJ实现.

它配置有: <aop:aspectj-autoproxy />. (官方文档)

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天全站免登陆