Spring Boot 事件监听器不接收事件

SpringBoot EventListener don't receive events

我的 EventListener 注释没有收到任何 Spring 事件。这是我的代码:

@Component
public class ProxyConfig {

    public ProxyConfig() {
        System.out.println("I can see this in the console");
    }

    @EventListener
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        System.out.println("WON'T WORK :-(");  // FIXME
    }

    @EventListener
    public void test(ApplicationStartedEvent event) {
        System.out.println("WON'T WORK :-(");  // FIXME
    }
}

这是我的 Application class:

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(MyApp.class, args);
    }
}

根据 https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2 and https://solidsoft.wordpress.com/2015/09/29/annotation-driven-event-listeners-in-spring-4-2/ 它一定能正常工作,但它仍然无法打印我的 "WON'T WORK :-(" 字符串 :(

有什么想法吗?

谢谢!

您正在侦听的两个事件都在应用程序生命周期的早期发布。

ApplicationStartedEvent发送"as early as conceivably possible as soon as a SpringApplication has been started - before the Environment or ApplicationContext is available, but after the ApplicationListeners have been registered"。

ApplicationEnvironmentPreparedEvent 已发布 "when a SpringApplication is starting up and the Environment is first available for inspection and modification."

在这两种情况下,事件发布得太早,无法通过注释和应用程序上下文找到侦听器。正如您所观察到的,您可以使用 spring.factories 来注册您的侦听器。或者,您可以在 SpringApplication.

上使用 setter 方法