为什么这个Spring AOP切入点没有被触发? [英] why is this Spring AOP pointcut not triggered?

查看:186
本文介绍了为什么这个Spring AOP切入点没有被触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写非常基于模式的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 / strong>其中包含方法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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆