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

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

问题描述

我在我的应用程序中编写了几个Aspects。所有其他人的工作除以下情况外。

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){
       ...
    }
}

当我尝试执行发送方法调试点没有被点击执行

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

UPDATE

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

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)它运作正常。但是由于回复方法在内部调用send方法,它不应该调用方面吗?

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 清除东西起来。仅仅为了SO的未来开发人员的信息目的,我发布了这个问题的完整答案



让我们假设有一个来自的SimplePojo

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

当我们调用方法 foo()时,它重新调用方法 bar()在里面。即使从AOP代理调用方法 foo() 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(),则无法调用

解决方案

使用 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

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

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