![](/img/trans.png)
[英]Spring AOP: pointcut @annotation(MyAnnotation) && call(..) is not triggered as expected
[英]why is this Spring AOP pointcut not triggered?
我正在編寫非常基於模式的Spring AOP,這里是.xml
<bean id="aoplistener" class="tao.zhang.Listener"/>
<aop:config>
<aop:aspect ref="aoplistener">
<aop:pointcut id="whenCalled" expression="execution(* callme(..))" />
<aop:after method="scream" pointcut-ref="whenCalled" />
</aop:aspect>
</aop:config>
tao.zhang.Listener中的方法scream()只打印出一些文本, 並且應該在調用方法callme()時執行。
我有一個名為logger的bean,它有方法log()和callme()
public void log(){
callme();
System.out.println("Hello from logger ~~~~~~~~~~~~~~~~~~~");
}
public void callme(){
System.out.println("I'm called");
}
請注意,callme()由log()調用
現在我有一個調度程序,每5秒調用一次log():
<task:scheduler id="myScheduler" pool-size="10"/>
<task:scheduled-tasks scheduler="myScheduler">
<task:scheduled ref="logger" method="log" fixed-rate="5000"/>
</task:scheduled-tasks>
奇怪的是,沒有調用scream() ,但是如果直接調用callme():
<task:scheduler id="myScheduler" pool-size="10"/>
<task:scheduled-tasks scheduler="myScheduler">
<task:scheduled ref="logger" method="callme" fixed-rate="5000"/>
</task:scheduled-tasks>
scream()被調用!
有什么建議么? 在我看來,這個切入點與另一個方法中調用的方法不匹配......
Spring AOP僅在通過bean句柄完成調用時捕獲方法調用(因為攔截器是通過使用代理對象來應用的),而不是在直接調用方法時。
為了使你的代碼工作,你需要切換到使用AspectJ(它通過重寫類的字節碼,它允許它攔截更多的東西,並更透明地這樣做)或更改你調用callme()
以便它通過bean句柄:
SomeClass selfRef;
public void log(){
selfRef.callme();
System.out.println("Hello from logger ~~~~~~~~~~~~~~~~~~~");
}
public void callme(){
System.out.println("I'm called");
}
您需要顯式配置selfRef
字段; 它不會被自動裝配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.