Run code at Spring Boot startup

To execute some code when the Spring Boot application startup simply add the following ApplicationStartup class somewhere in your project (e.g. in the root package) and put your custom code inside the onApplicationEvent method.

Note that you can name the class as you want, ApplicationStartup is just an example.

Spring Boot 1.3.0 or later

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class ApplicationStartup 
implements ApplicationListener<ApplicationReadyEvent> {

  /**
   * This event is executed as late as conceivably possible to indicate that 
   * the application is ready to service requests.
   */
  @Override
  public void onApplicationEvent(final ApplicationReadyEvent event) {
 
    // here your code ...
 
    return;
  }
 
} // class

Previous versions (less than Spring Boot 1.3.0)

The ApplicationReadyEvent class is available from Spring Boot 1.3.0 or later, in previous versions you can use ContextRefreshedEvent.

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class ApplicationStartup 
implements ApplicationListener<ContextRefreshedEvent> {

  /**
   * This method is called during Spring's startup.
   * 
   * @param event Event raised when an ApplicationContext gets initialized or
   * refreshed.
   */
  @Override
  public void onApplicationEvent(final ContextRefreshedEvent event) {
 
    // here your code ...
 
    return;
  }
 
} // class

References

http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/event/ApplicationReadyEvent.html
https://stackoverflow.com/questions/6684451/executing-a-java-class-at-application-startup-using-spring-mvc
http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/context/ApplicationListener.html
https://stackoverflow.com/questions/2401489/execute-method-on-startup-in-spring
https://stackoverflow.com/questions/9680286/spring-web-application-doing-something-on-startup-initialization
https://springframework.guru/running-code-on-spring-boot-startup/

  • Damian Blazejewski

    This event will be executed also when the context is refreshed.
    ContextStartedEvent is executed only when the context is started.
    You also have Spring Boot event ApplicationReadyEvent which better indicates that the application has started and is ready to service requests.

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2019 Netgloo