about https://github.com/spring-projects/spring-boot/pull/31958
demo code: demo.zip
I want to initialize a few things before the WebServer starts.
The reason we don't use ApplicationPreparedEvent is because it can't capture events using the @EventListener Annotation,
And @Autowired cannot be used when using the ApplicationListener interface,otherwise it will cause NPE。
Please look at the listener: com.example.demo.AppInitializer2
Please look at the listener: com.example.demo.AppInitializer
Comment From: weiwei121723
@philwebb Please follow this issue, thanks a lot
Comment From: wilkinsona
The reason we don't use
ApplicationPreparedEventis because it can't capture events using the@EventListenerannotation.
ApplicationPreparedEvent is published before the application context has been refreshed and before any beans have been created. As a result, a listener for ApplicationPreparedEvent cannot be a @Component.
And
@Autowiredcannot be used when using theApplicationListenerinterface otherwise it will cause NPE
The NPE occurs because you have created AppInitializer yourself (new AppInitializer()) and have not set its myApp field.
I don't think we have an event at the moment that can be received by a bean and is published before the web server is started. What sort of things do you want to initialize before the web server starts? Why do you want to do this initialization in response to an event? I'm wondering if you could use InitializingBean , @PostConstruct, and SmartLifecycle or similar instead.
Comment From: JialeHe
@wilkinsona
Thank you very much!
After testing this we decided to use @PostConstruct to solve this problem.
We still have a question
Why is SpringBoot 1.5.xcompared to 2.6.x
ContextRefreshedEvent made changes to the sequence of WebServerInitializedEvent event to send.
What's the reason for this change?
Our review of the source code confirms this.
Comment From: snicoll
Thanks for letting us know that @PostConstruct works for you.
What's the reason for this change?
Spring Boot 1.5.x is EOL so I am afraid we can justify taking the time to answer that question. Besides, as mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.
Comment From: JialeHe
@snicoll Thank you for your answer~
We just upgraded from 1.5.x to 2.6.x this year.
My function was working on 1.5.x, but after upgrading to 2.6.x the problem occurred.
Although @PostConstruct currently solves my problem, if the SpringBoot release upgrade process causes my function to fail again, I will find another solution.
My suggestion is to add a WebServerBeforeStartEvent to make the process clearer and more transparent.
Comment From: snicoll
Although @PostConstruct currently solves my problem
We've been discussing this on the PR and here. @PostConstruct is a more reliable way to do what you want compared to a event, regardless of what you've experienced upgrading.