Issue
my EventListener
annotation don't receive any Spring Event. Here is my code:
@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
}
}
And here is my Application
class:
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(MyApp.class, args);
}
}
According to 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/ it must be working, but it still not print my "WON'T WORK :-(" String :(
Any idea?
Thanks!
Solution
The two events that you are listening for are both published very early in an application's lifecycle.
ApplicationStartedEvent
is sent "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
is published "when a SpringApplication is starting up and the Environment is first available for inspection and modification."
In both cases, the event is published too early for a listener to be found via annotations and the application context. As you've observed you can use spring.factories
to register your listener. Alternatively, you can use the setter method on SpringApplication
.
Answered By - Andy Wilkinson
Answer Checked By - Pedro (JavaFixing Volunteer)