To run specific logic right after your Spring Boot application starts, you can use one of the following standard interfaces provided by Spring:
1. Using CommandLineRunner
- This interface runs after the Spring context is fully loaded.
- You get access to
String[] args.
Example:
@Component
public class StartupRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Application started. Running post-startup logic.");
// your custom logic here
}
}
2. Using ApplicationRunner
- Similar to
CommandLineRunner, but usesApplicationArgumentswhich gives more structured access to arguments.
Example:
@Component
public class AppStartupRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Startup logic with ApplicationRunner");
// your logic here
}
}
3. Using @EventListener(ApplicationReadyEvent.class)
- This runs after the entire Spring Boot app has started, including the web server.
- Ideal for logic that depends on the app being fully ready to serve requests.
Example:
@Component
public class StartupEventListener {
@EventListener(ApplicationReadyEvent.class)
public void onApplicationReady() {
System.out.println("Application is ready. Running post-startup event logic.");
// your logic here
}
}
When to Use Which?
| Use Case | Recommended Interface |
|---|---|
| Need command-line arguments | CommandLineRunner or ApplicationRunner |
| Need to execute logic after Spring context initialization but before accepting HTTP requests | CommandLineRunner |
| Need to execute logic after everything (including embedded Tomcat or Jetty) is fully up | @EventListener(ApplicationReadyEvent.class) |
