Spring AOP不能在另一个方法内部进行方法调用 [英] Spring AOP not working for method call inside another method

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

问题描述

ABC.java

public void method1(){
   .........
   method2();
  ...........
}


public void method2(){
  ...............
  ...............  
}

我希望在 method2 的电话上安排AOP。所以,
我创建了一个类 AOPLogger.java ,方法中提供的方面功能 checkAccess

在配置文件中,我执行了类似下面的操作

I want to have AOP on call of method2.So, I created one class,AOPLogger.java,having aspect functionality provided in a method checkAccess
In configuration file, I did something like below

<bean id="advice" class="p.AOPLogger" />
<aop:config>
  <aop:pointcut id="abc" expression="execution(*p.ABC.method2(..))" />
  <aop:aspect id="service" ref="advice">
    <aop:before pointcut-ref="abc" method="checkAccess" />          
  </aop:aspect>
</aop:config>

但是当调用我的方法2时,不会调用AOP功能,即 checkAccess 方法没有被AOPLogger类调用。

But when my method2 is called, AOP functionality is not getting invoked i.e. checkAccess method is not getting invoked of AOPLogger class.

我遗失的任何东西?

推荐答案

方面应用于bean周围的代理。请注意,每次获得对bean的引用时,它实际上不是您的配置中引用的类,而是实现相关接口的合成类,委托给实际的类并添加功能,例如您的AOP。

The aspect is applied to a proxy surrounding the bean. Note that everytime you get a reference to a bean, it's not actually the class referenced in your config, but a synthetic class implementing the relevant interfaces, delegating to the actual class and adding functionality, such as your AOP.

在上面的示例中,您在类上直接调用 ,而如果该类实例作为Spring bean注入到另一个类中,则将其作为代理注入,并且因此,将在代理上调用方法调用(并且将触发方面)

In your above example you're calling directly on the class, whereas if that class instance is injected into another as a Spring bean, it's injected as its proxy, and hence method calls will be invoked on the proxy (and the aspects will be triggered)

如果要实现上述目的,可以拆分 method1 / method2 进入单独的bean,或使用非弹簧导向的AOP框架。

If you want to achieve the above, you could split method1/method2 into separate beans, or use a non-spring-orientated AOP framework.

Spring doc 详细说明了这一点,以及几个解决方法(包括我上面的第一个建议)

The Spring doc details this, and a couple of workarounds (including my first suggestion above)

这篇关于Spring AOP不能在另一个方法内部进行方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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