Spring interceptor cannot intercept method calls inside the class

When using the spring framework, the spring interceptor is the most used feature. In general, we use annotations to use interception, such as transaction annotation @Transactional. But for method calls inside the class, the interceptor is invalid.

Specific examples are as follows:

package com.juying.test

public class TestAop {
    public void test1() {
        test2();
        test3();
    }

    public void test2() {
        System.out.println("test2");
    }

    public void test3() {
        System.out.println("test3");
    }
}

Interceptor

@Aspect
public class TheAspect {
    @Before("execution(* com.juying.test.TestAop.*(..))")  
    public void checkData() {
        System.out.println("checkData");
    }
}

When the test1 method in the TestAop class is executed, checkData will be output only once.

Reason: The interceptor is realized by dynamic proxy. Dynamic proxy is to generate a new proxy class. All the information has changed (class name, package name), so it cannot be intercepted.

public class TestAopXxxxx+地址 {
    public void test1() {
        test2();
        test3();
    }

    public void test2() {
        System.out.println("test2");
    }

    public void test3() {
        System.out.println("test3");
    }
}

Solutions:
1. Migrate the methods that need to be intercepted to other classes
2. Call through @Autowired injection instead of using this

Published 190 original articles · 19 praises · 200,000+ views

Guess you like

Origin blog.csdn.net/zengchenacmer/article/details/78207559