Home  >  Article  >  Java  >  Why Doesn\'t My Spring AOP Intercept Method Calls Within Another Method?

Why Doesn\'t My Spring AOP Intercept Method Calls Within Another Method?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 16:54:30151browse

Why Doesn't My Spring AOP Intercept Method Calls Within Another Method?

Spring AOP Fails to Intercept Method Call within Another Method

Consider two methods defined in ABC.java:

<br>public void method1() {</p>
<pre class="brush:php;toolbar:false">method2();

}

public void method2() {}

To apply AOP on method2 calls, you have defined an AOPLogger.java class with an checkAccess aspect method. In your configuration file:

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


However, when method2 is invoked, the checkAccess method in AOPLogger is not triggered.

Explanation

The AOP aspect is applied to a proxy surrounding the bean. When you obtain a reference to a bean, you are not actually working with the class specified in your configuration. Instead, you are presented with a synthetic class that implements the appropriate interfaces, delegates calls, and provides additional functionality (e.g., your AOP).

In this case, you are directly invoking method2 on the class. If the instance of that class were injected into another bean as a Spring bean, it would be injected as the proxy. As a result, any method calls would be directed to the proxy (and the aspects would be triggered).

Solutions

To address this issue, consider the following options:

    <li>Separate method1 and method2 into distinct beans.</li>
    <li>Employ a non-Spring AOP framework.</li>

The Spring documentation (section "Understanding AOP Proxies") provides more information and possible workarounds, including the first recommendation above.

The above is the detailed content of Why Doesn\'t My Spring AOP Intercept Method Calls Within Another Method?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn