我正在尝试在 Spring MVC 中发布一个自定义事件,但是在加载上下文时没有触发,下面是代码片段,
onConnectionOpened 将在连接到使用@PostConstruct 初始化bean 后触发的服务器后调用
@Autowired
private ApplicationEventPublisher publisher;
public void onConnectionOpened(EventObject event) {
publisher.publishEvent(new StateEvent("ConnectionOpened", event));
}
我在下面的监听器部分使用注释
@EventListener
public void handleConnectionState(StateEvent event) {
System.out.println(event);
}
我能够看到在加载或刷新上下文后触发的事件,这是否预期可以在加载或刷新上下文后发布自定义应用程序事件?
我正在使用 Spring 4.3.10
提前致谢
最佳答案
@EventListener
注释由 EventListenerMethodProcessor
处理一旦所有 beans 被实例化并准备好,它将立即运行。当您从带注释的 @PostConstruct
方法发布事件时,可能不是所有的事情都在那个时刻启动并运行,并且尚未检测到基于 @EventListener
的方法.
相反,您可以使用 ApplicationListener
接口(interface)获取事件并处理它们。
public class MyEventHandler implements ApplicationListener<StateEvent> {
public void onApplicationEvent(StateEvent event) {
System.out.println(event);
}
}
关于java - 无法在上下文加载之前在 spring 中发布自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47271498/