Spring AOP 不工作,当在 bean 内部调用该方法时 [英] Spring AOP not working, when the method is called internally within a bean

查看:50
本文介绍了Spring AOP 不工作,当在 bean 内部调用该方法时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中编码了多个方面.除以下内容外,其他所有内容均有效.

I have several Aspects coded in my application. All others works except for the following.

服务接口

package com.enbiso.proj.estudo.system.service;
...
public interface MessageService {
     ...
     Message reply(Message message);
     Message send(Message message);
     ...
}

服务实施

package com.enbiso.proj.estudo.system.service.impl;
....
@Service("messageService")
public class MessageServiceImpl implements MessageService {
   ...
   @Override
   public Message reply(Message message) {
        ...
        return this.send(message);
   }

   @Override
   public Message send(Message message) {
         ...
   }
}

方面

@Aspect
@Component
public class NewMessageAspect {
    ...
    @AfterReturning(value = "execution(* com.enbiso.proj.estudo.system.service.impl.MessageServiceImpl.send(..))", 
                    returning = "message")
    public void perform(Message message){
       ...
    }
}

当我尝试执行 send 方法时,调试点没有在 perform 方面得到命中.

When I try to execute the send method the debug point is not getting hit in the aspect perform.

更新

我做了一些调查,发现这不起作用,当从 reply 方法调用 send 方法时,如下所示

I did some investigations and found that this doesn't work, when the send method is invoked from the reply method as below

@Autowire MessageService messageService;
...
messageService.reply(message);

但是如果我调用方法 messageService.send(message) 它工作正常.但是由于reply方法在内部调用send方法,不应该也调用aspect吗?

But if I call the method messageService.send(message) it works fine. But as reply method is calling send method internally, shouldn't it also invoke the aspect?

我不知道我做错了什么.请帮帮我.

I have no idea what i have done wrong. Please help me.

推荐答案

谢谢jst 把事情搞清楚.只是为了给未来的开发人员提供信息,我发布了这个问题的完整答案


让我们假设有一个来自 SimplePojo

public class SimplePojo implements Pojo {
    public void foo() {
        this.bar();
    }
    public void bar() {
        ...
    }
}

当我们调用方法 foo() 时,它会重新调用其中的方法 bar().即使认为方法 foo() 是从 AOP 代理调用的,bar() 的内部调用也没有被 AOP 代理覆盖.

When we call the method foo(), it reinvokes the method bar() inside it. Even thought the method foo() is invoked from the AOP Proxy, the internal invocation of the bar() is not covered by the AOP Proxy.

所以最终这使得,如果有任何建议附加到方法 bar() 不被调用

So eventually this makes, if there are any advices attached to the method bar() to not get invoked

解决方案

使用 AopContext.currentProxy() 调用该方法.不幸的是,这将逻辑与 AOP 结合起来.

Use AopContext.currentProxy() to call the method. Unfortunately this couples the logic with AOP.

public void foo() {
   ((Pojo) AopContext.currentProxy()).bar();
}

参考:

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-understanding-aop-proxies

这篇关于Spring AOP 不工作,当在 bean 内部调用该方法时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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