You have several choices:
Using CommandLineRunner
or ApplicationRunner
as a Bean definition:
Spring Boot executes these towards the end of the application startup process. In most circumstances, the CommandLineRunner
will do the job. Following is an example of a CommandLineRunner implementation with Java 8:
@Bean
public CommandLineRunner commandLineRunner() {
return (args) -> System.out.println("Hello World");
}
Note that the args
is the String array of arguments. You can also provide an implementation of this interface and define it as a Spring Component:
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Hello World");
}
}
You can use the ApplicationRunner
if you need better argument management. ApplicationRunner takes an ApplicationArguments
instance that has enhanced argument management options.
You can also order the CommandLineRunner
and ApplicationRunner
beans using Spring's @Order
annotation:
@Bean
@Order(1)
public CommandLineRunner commandLineRunner() {
return (args) -> System.out.println("Hello World, Order 1");
}
@Bean
@Order(2)
public CommandLineRunner commandLineRunner() {
return (args) -> System.out.println("Hello World, Order 2");
}
Using Spring Boot's ContextRefreshedEvent:
Spring Boot publishes several events at startup. These events indicate the completion of a phase in the application startup process. You can listen to the ContextRefreshedEvent
and execute custom code:
@EventListener(ContextRefreshedEvent.class)
public void execute() {
if(alreadyDone) {
return;
}
System.out.println("hello world");
}
ContextRefreshedEvent
is published several times. Thus, ensure to put a check whether the code execution is already finished.