mooor
mooor

Reputation: 347

No Application Events in the 'before ApplicationContext' phase are triggered

I am trying to listen to the ApplicationStartingEvent (or any of the pre-ApplicationContext phase) but it looks like none of them is ever fired.

Tried to set a breakpoint in the onApplicationEvent method, tried to print the event to the standard output. none works

the listener:

public class MyListener implements ApplicationListener<ApplicationEvent> {

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        System.out.println("Application event " + applicationEvent);
    }
}

the application:

@SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication();
        springApplication.addListeners(new MyListener());
        springApplication.run(MySpringBootApplication.class, args);

    }
}

Expect to see some events to be printed out to the console. Thanks for help

Upvotes: 1

Views: 461

Answers (1)

Andy Wilkinson
Andy Wilkinson

Reputation: 116091

The run method that you have called is a static method. This means that the state of your springApplication instance, including the listener that you have added, has no effect.

You should do something like this instead:

SpringApplication springApplication = new SpringApplication(MySpringBootApplication.class);
springApplication.addListeners(new MyListener());
springApplication.run(args);

Upvotes: 1

Related Questions