Home > Java > javaTutorial > body text

Why is my AOP Aspect Not Invoked in Nested Method Calls?

Susan Sarandon
Release: 2024-10-31 15:51:02
Original
384 people have browsed it

Why is my AOP Aspect Not Invoked in Nested Method Calls?

Nested Method Calls and Spring AOP

Consider the following code in ABC.java:

<code class="java">public void method1() {
    // ...
    method2();
    // ...
}

public void method2() {
    // ...
    // ...
}</code>
Copy after login

Adding AOP to method2 involves creating an aspect, AOPLogger, containing a method for checking access, checkAccess. The Spring configuration includes:

<code class="xml"><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></code>
Copy after login

However, the aspect, checkAccess, is not invoked when method2 is called. What's missing?

AOP Proxies and Bean Injections

AOP works by applying aspects to proxies surrounding the bean. When a bean is referenced, it's not the instantiated class but a synthetic one that delegates to the actual class and adds functionalities like AOP.

In the example, method2 is called directly on the class. When injected as a Spring bean, the enclosing class is injected as its proxy, triggering the aspects on method calls.

To invoke AOP on nested method calls, consider the following options:

  1. Bean Separation: Split method1 and method2 into separate beans.
  2. Non-Spring AOP Framework: Utilize a non-Spring-oriented AOP framework for more granular control over aspect application.

The Spring documentation provides further details and potential workarounds.

The above is the detailed content of Why is my AOP Aspect Not Invoked in Nested Method Calls?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template