Spring ApplicationListener 未接收事件
我有以下 ApplicationListener:
package org.mycompany.listeners;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;
public class MyApplicationListener implements ApplicationListener<ContextStartedEvent> {
public MyApplicationListener() {
super();
System.out.println("Application context listener is created!");
}
/**
* {@inheritDoc}
*/
public void onApplicationEvent(final ContextStartedEvent event) {
System.out.println("Context '" + event.getApplicationContext().getDisplayName() + "' is started!");
}
}
和以下 bean 定义:
<bean name="myApplicationListener" class="org.mycompany.listeners.MyApplicationListener" />
我可以看到 bean 是在打印来自构造函数的消息时创建的,但从未收到上下文启动事件。我缺少什么?
I have the following ApplicationListener:
package org.mycompany.listeners;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;
public class MyApplicationListener implements ApplicationListener<ContextStartedEvent> {
public MyApplicationListener() {
super();
System.out.println("Application context listener is created!");
}
/**
* {@inheritDoc}
*/
public void onApplicationEvent(final ContextStartedEvent event) {
System.out.println("Context '" + event.getApplicationContext().getDisplayName() + "' is started!");
}
}
And the following bean definition:
<bean name="myApplicationListener" class="org.mycompany.listeners.MyApplicationListener" />
I can see that bean is created as message from the constructor is printed, but context start event is never recieved. What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您在上下文上显式调用 ConfigurableApplicationContext.start() 时,会发布 ContextStartedEvent 。如果您需要在初始化上下文时发布事件,请使用 ContextRefreshedEvent。
另请参阅:
ContextStartedEvent
is published when you explicitly invokeConfigurableApplicationContext.start()
on the context. If you need an event that is published when context is initialized, useContextRefreshedEvent
.See also:
由于您没有延迟加载的bean(根据您的说法),那么您很可能出于错误的原因使用事件,并且可能应该使用类似 InitializingBean 接口:
来自 Spring 手册:
来源: Spring 框架 - 生命周期回调
Since you have no lazy loaded beans (according to you) then you are most likely using events for the wrong reason and probably should use something like InitializingBean interface instead:
From Spring manual:
Source: Spring Framework - Lifecycle callbacks
不确定这是否有帮助,但我隐约记得有类似的问题,这是通过预加载而不是延迟加载解决的。这是两者的快速概述
Not sure if this helps, but I vaguely remember having a similar problem, which was solved by preloading and not lazy loading. Here's a quick overview of both