2013-01-01 78 views
3

我是Spring AOP的新手。
使用基于注解的Spring配置: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框架本身召集所有公共的方法呢? (如TestComponent.init()创建由Spring的TestComponent实例的过程中) 目前我只能够TestComponent.testMethod()通过调用拦截:

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

回答

4

这是您遇到的Spring AOP常见问题。 Spring通过代理建议的类来完成AOP。在你的情况下,你的TestComponent实例将被包装在一个运行时代理类中,该代理类为要应用的任何方面建议提供“挂钩”。当从以外的类中调用方法时,此方法运行良好,但您发现它不适用于内部呼叫。原因是内部呼叫不会通过代理屏障,因此不会触发该方面。

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

另一种方式是使用称为加载时编织的东西。当使用这种方式时,通过将类型代码注入类定义中,自定义类加载器将AOP建议添加到类(“编入”)中。 Spring文档有这个more

还有第三种方法叫做“编译时编织”。在这种情况下,编译它时,您的AOP建议将静态编入每个建议的类中。