Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring AOP不拦截Spring';s容器_Java_Spring_Aop - Fatal编程技术网

Java Spring AOP不拦截Spring';s容器

Java Spring AOP不拦截Spring';s容器,java,spring,aop,Java,Spring,Aop,我是Spring AOP的新手。 使用基于注释的Spring配置: @Configuration @EnableAspectJAutoProxy(proxyTargetClass=true) @ComponentScan({"sk.lkrnac"}) 方面: @Aspect @Component public class TestAspect { @Before("execution(* *(..))") public void logJoinPoint(JoinPoint j

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

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass=true)
@ComponentScan({"sk.lkrnac"})
方面:

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

}
弹簧组件:

package sk.lkrnac.testaop;

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

    public void testMethod() {
        return;
    }
}
如何拦截Spring框架本身调用的所有公共方法?(例如,在Spring创建TestComponent实例期间使用TestComponent.init() 目前,我只能通过调用以下命令截获
TestComponent.testMethod()

TestComponent testComponent = springContext.getBean(TestComponent.class);
testComponent.testMethod();

如果没有任何明确的方法,您无法拦截
init()
,请参阅以了解详细信息。

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

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

另一种方法是使用称为加载时编织的方法。使用此方法时,通过向类定义中注入字节码,自定义类加载器将AOP建议添加到类中(“编织到”类中)。Spring文档对此进行了详细说明


还有第三种方法,称为“编译时编织”。在这种情况下,编译时,AOP建议会静态地编织到每个建议类中。

您还可以尝试通过代理对象(如中所述)从init()调用内部testMethod()