2013-01-01 77 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建議將靜態編入每個建議的類中。