ContextStartedEvent未在Spring Boot上广播

时间:2016-07-05 14:57:19

标签: spring-boot

我正在将应用程序迁移到Spring启动。我的应用程序在ContextStartedEvent上侦听,但它看起来Spring启动不会发出此类事件。我可以更改我的应用并在ApplicationReadyEvent上收听,但根据spring boot doc,仍会发出“旧”事件。

我希望尽可能保持代码不变。

问题:Spring Boot是否支持ContextStartedEvent?

演示:

@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

1 个答案:

答案 0 :(得分:2)

调用ContextStartedEvent时会发送ApplicationContext.start()。但是SpringApplication.run()不会调用start(),而只会调用refresh()。如果您希望发送ContextStartedEvent,则需要启动上下文。例如:

public static void main(String[] args) throws Exception {
    SpringApplication.run(EventExample.class, args).start();
}