Home  >  Article  >  Java  >  How to Execute Code After Spring Boot Application Startup?

How to Execute Code After Spring Boot Application Startup?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 15:42:03886browse

How to Execute Code After Spring Boot Application Startup?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn