ContextStartedEvent 未在 Spring Boot 上广播 [英] ContextStartedEvent not broadcasted on Spring Boot
问题描述
我正在将应用程序迁移到 Spring Boot.我的应用程序监听 ContextStartedEvent
但看起来 Spring boot 没有发出这样的事件.我可以更改我的应用程序并监听 ApplicationReadyEvent
,但根据 spring boot doc,仍然会发出旧"事件.
I'm migrating application to Spring boot. My application listen on ContextStartedEvent
but it looks that Spring boot does not emit such event. I can change my application and listen on ApplicationReadyEvent
, but according to spring boot doc, "old" events are still emitted.
我希望尽可能保持我的代码不变.
I would like to keep my code unchanged as much as possible.
问题:Spring Boot 是否支持 ContextStartedEvent?
Question: Is ContextStartedEvent supported by Spring Boot or not?
演示:
@EnableAutoConfiguration
public class EventExample {
@EventListener(classes = ContextStartedEvent.class)
void start() { System.out.println("Listen ContextStartedEvent");} //not called
@EventListener(classes = ApplicationReadyEvent.class)
void start2(){System.out.println("Listen ApplicationReadyEvent");} //called
public static void main(String[] args) throws Exception {
SpringApplication.run(EventExample.class, args);
}
}
输出
监听 ApplicationReadyEvent
Listen ApplicationReadyEvent
推荐答案
ContextStartedEvent
在 ApplicationContext.start()
被调用时发送.但是SpringApplication.run()
不调用start()
,它只调用refresh()
.如果您希望 ContextStartedEvent
被发送,那么您需要启动上下文.例如:
The ContextStartedEvent
is sent when ApplicationContext.start()
is called. However SpringApplication.run()
doesn't call start()
, it only calls refresh()
. If you want ContextStartedEvent
to be sent then you'll need to start the context. For example:
public static void main(String[] args) throws Exception {
SpringApplication.run(EventExample.class, args).start();
}
这篇关于ContextStartedEvent 未在 Spring Boot 上广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!