为什么Spring在通过XML声明bean时运行@Scheduled方法,而不是在通过注释发现bean时运行@Scheduled方法?
我希望每10秒运行一次任务。当我在为什么Spring在通过XML声明bean时运行@Scheduled方法,而不是在通过注释发现bean时运行@Scheduled方法?,spring,scala,Spring,Scala,我希望每10秒运行一次任务。当我在applicationContext.xml文件中声明Bean时,一切都按预期工作。当我简单地用@Component注释Bean时,任务永远不会执行。我的代码/配置如下所示: QueueProcessor.scala package example.components // imports removed for brevity @Component class QueueProcessor { @Scheduled(fixedDelay = 100
applicationContext.xml
文件中声明Bean时,一切都按预期工作。当我简单地用@Component
注释Bean时,任务永远不会执行。我的代码/配置如下所示:
QueueProcessor.scala
package example.components
// imports removed for brevity
@Component
class QueueProcessor {
@Scheduled(fixedDelay = 10000)
def poll() = {
println("polling queue")
}
}
applicationContext.xml
<context:component-scan base-package="example.components" />
<task:executor id="genericExecutor" pool-size="2" />
<task:scheduler id="genericScheduler" pool-size="2" />
<task:annotation-driven executor="genericExecutor" scheduler="genericScheduler" />
如果我只是在我的applicationContext.xml
中添加一行
,那么任务将按预期每10秒执行一次。我已经验证了示例.components
包中的其他类是通过注释实例化的,所以这个类没有被发现不应该是问题所在
还有什么其他可能的错误吗
编辑:我将行
移动到我的servlet.xml
文件中。这就解决了问题。这与文件的读取顺序有关吗?你的问题真的让我很困惑。我有一个几乎相同设置的工作示例。当您使用注释时,它似乎没有被当作Springbean来使用。能否通过注释将依赖项注入QueueProcessor类,并查看其是否有效?这至少会告诉我们,它是否被适当地作为SpringBean使用。要使annotation工作正常,请尝试添加以下行:
<context:annotation-config/>
这应该能奏效
另请参见:如编辑的问题中所述,将行
移动到servlet.xml
文件解决了此问题。即使是组件扫描也会做同样的事情-重新启动AutowiredNotationBeanPostProcessor
-并且xml已经有组件扫描,所以我怀疑这是否会有帮助。你有多个Spring上下文文件吗?是的,注入依赖项起作用了。我将在编辑中添加这一点,但我发现在servlet文件中放置
行解决了这个问题。