Spring AOP 不适用于另一个方法中的方法调用 [英] Spring AOP not working for method call inside another method

查看:33
本文介绍了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>

但是当我的 method2 被调用时,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.

有什么我遗漏的吗?

推荐答案

aspect 应用于围绕 bean 的 proxy.请注意,每次获得对 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,或者使用一个非面向spring的AOP框架.

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

Springdoc(了解 AOP 代理"部分) 详细说明了这一点,以及一些解决方法(包括我上面的第一个建议)

The Spring doc (section "Understanding AOP Proxies") details this, and a couple of workarounds (including my first suggestion above)

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

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