Running code after Spring Boot starts Running code after Spring Boot starts java java

Running code after Spring Boot starts


It is as simple as this:

@EventListener(ApplicationReadyEvent.class)public void doSomethingAfterStartup() {    System.out.println("hello world, I have just started up");}

Tested on version 1.5.1.RELEASE


Try:

@Configuration@EnableAutoConfiguration@ComponentScanpublic class Application extends SpringBootServletInitializer {    @SuppressWarnings("resource")    public static void main(final String[] args) {        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);        context.getBean(Table.class).fillWithTestdata(); // <-- here    }}


Have you tried ApplicationReadyEvent?

@Componentpublic 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;  }}

Code from: http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/

This is what the documentation mentions about the startup events:

...

Application events are sent in the following order, as your application runs:

An ApplicationStartedEvent is sent at the start of a run, but beforeany processing except the registration of listeners and initializers.

An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known, but before the contextis created.

An ApplicationPreparedEvent is sent just before the refresh is started, but after bean definitions have been loaded.

An ApplicationReadyEvent is sent after the refresh and any related callbacks have been processed to indicate the application is ready toservice requests.

An ApplicationFailedEvent is sent if there is an exception on startup.

...