为什么这个 Spring AOP 切入点没有触发? [英] why is this Spring AOP pointcut not triggered?
问题描述
我正在编写非常基本的基于模式的 Spring AOP,这是 .xml
I'm writing very basic schema-based Spring AOP, here's the .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() 方法时执行.
The method scream() in tao.zhang.Listener just prints out some text, and is supposed to be executed whenever a method callme() is called.
我有一个名为 logger 的 bean,它有 log() 和 callme() 方法
I have a bean called logger which has the methods log() and callme()
public void log(){
callme();
System.out.println("Hello from logger ~~~~~~~~~~~~~~~~~~~");
}
public void callme(){
System.out.println("I'm called");
}
注意 callme() 是由 log() 调用的
Note that callme() is called by log()
现在我有一个调度程序,它每 5 秒调用一次 log():
Now I have a scheduler which calls log() every 5 seconds:
<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():
Strangely, scream() is not invoked, but if callme() is called directly:
<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() 被调用!
有什么建议吗?在我看来,这个切入点与另一个方法中调用的方法不匹配......
Any suggestions? It seems to me that this pointcut doesn't match methods called inside another method ...
推荐答案
Spring AOP 只在通过 bean 句柄完成调用时捕获方法调用(因为拦截器是通过使用代理对象应用的)而不是在方法被直接调用.
Spring AOP only traps a method call when the call is done through a bean handle (because the interceptor is applied through the use of a proxy object) and not when the method is called directly.
为了让你的代码工作,你需要切换到使用 AspectJ(它通过重写类的字节码来工作,它允许它拦截更多的东西并且更透明地这样做)或者改变你调用 的方式callme()
所以它是通过一个 bean 句柄:
To make your code work, you need to either switch to using AspectJ (which works by rewriting the class's bytecode, which allows it to intercept far more things and to do so more transparently) or to change how you call callme()
so that it is via a bean handle:
SomeClass selfRef;
public void log(){
selfRef.callme();
System.out.println("Hello from logger ~~~~~~~~~~~~~~~~~~~");
}
public void callme(){
System.out.println("I'm called");
}
您需要显式配置selfRef
字段;它不会自动装配.
You need to configure the selfRef
field explicitly; it won't be autowired.
这篇关于为什么这个 Spring AOP 切入点没有触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!