Spring AOP不拦截Spring容器中的方法

lub*_*nac 3 java aop spring

我是Spring AOP的新手.
使用基于注释的Spring配置:

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass=true)
@ComponentScan({"sk.lkrnac"})
Run Code Online (Sandbox Code Playgroud)

方面:

@Aspect
@Component
public class TestAspect {
    @Before("execution(* *(..))")
    public void logJoinPoint(JoinPoint joinPoint){
        ....
    }

}
Run Code Online (Sandbox Code Playgroud)

弹簧组件:

package sk.lkrnac.testaop;

@Component
public class TestComponent{
    @PostConstruct
    public void init(){
        testMethod();
    }

    public void testMethod() {
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何拦截Spring框架本身调用的所有公共方法?(例如,Spring创建TestComponent实例时的TestComponent.init())目前我只能TestComponent.testMethod()通过调用来拦截:

TestComponent testComponent = springContext.getBean(TestComponent.class);
testComponent.testMethod();
Run Code Online (Sandbox Code Playgroud)

pap*_*pap 5

这是Spring AOP遇到的常见问题.Spring通过代理建议的类来完成AOP.在您的情况下,您的TestComponent实例将包装在运行时代理类中,该类为要应用的任何方面建议提供"挂钩".当从类外部调用方法时,这非常有效,但是正如您所发现的那样,它不适用于内部调用.原因是内部调用不会通过代理屏障,因此不会触发方面.

主要有两种方法.一种是从上下文中获取(代理)bean的实例.这是你已经尝试过的成功.

另一种方法是使用称为加载时编织的东西.使用它时,AOP建议通过将字节代码注入类定义,由自定义类加载器添加到类("编织"到其中).Spring文档对此有更多了解.

还有第三种方法,称为"编译时编织".在这种情况下,在编译时,您的AOP建议会静态编织到每个建议的类中.