Executing Code at Spring Boot Launch Time
Question:
How can I run code after my Spring Boot application has started up? I've attempted to initiate a new thread, but the required @Autowired services are not yet initialized at that time. I've also discovered the ApplicationPreparedEvent, which triggers before the annotations are set. Is there a more appropriate event or method for executing code once the application is ready to receive HTTP requests?
Answer:
An effective solution to this problem is to utilize the ApplicationReadyEvent:
<code class="java">@EventListener(ApplicationReadyEvent.class) public void doSomethingAfterStartup() { System.out.println("hello world, I have just started up"); }</code>
When tested with Spring Boot version 1.5.1.RELEASE, it was successfully tested and functioned after start-up. This method allows you to execute code once the application is fully initialized and ready to handle HTTP requests.
The above is the detailed content of How to Execute Code After Spring Boot Application Startup?. For more information, please follow other related articles on the PHP Chinese website!