Using CommandLineRunner and ApplicationRunner in Spring Boot

In Spring Boot, sometimes you want to run some code right after the application startsβ€”such as initializing data, setting up caches, or calling external services.

Spring Boot provides two interfaces for this:

  • CommandLineRunner
  • ApplicationRunner

Both are functional interfaces that let you execute logic after the SpringApplication.run(...) method is complete.

Using CommandLineRunner and ApplicationRunner in Spring Boot

🧠 Why Use CommandLineRunner and ApplicationRunner in Spring Boot?

Here are common use cases:

  • Seeding a database
  • Running background tasks
  • Verifying configuration
  • Logging app metadata at startup
  • Connecting to external services (Kafka, Redis, etc.)

πŸ› οΈ 1. Using CommandLineRunner

πŸ“¦ Interface:

βœ… Example:

This code will run once after the app starts and prints the command-line arguments.

πŸ› οΈ 2. Using ApplicationRunner

πŸ“¦ Interface:

βœ… Example:

You can start your app like this:

And get output like:

πŸ” Key Differences

FeatureCommandLineRunnerApplicationRunner
Argument TypeSimple String[]ApplicationArguments object
Argument ParsingManualStructured parsing available
Best ForSimple, quick start-up logicWhen argument parsing is needed
InputRaw valuesNamed/option args via --key=value

Both are called after the Spring ApplicationContext is fully initialized.

πŸ’‘ Using Lambda Style (Java 8+)

You can also define runners using lambda syntax inside your main class:

πŸ§ͺ Real-World Use Case: Seeding a Database

βœ… Best Practices

TipWhy
Use @Component or @BeanFor automatic registration
Use ApplicationRunner for structured argsEasier command-line parsing
Avoid heavy operationsStartup code should be quick
Use @Order if you need orderingControl the execution sequence of runners
Log errors properlyAvoid crashing the app on startup

🧭 Ordering Multiple Runners

If you have multiple runners and want to control their execution order:

🧘 Optional: Conditional Execution

You can conditionally enable or disable a runner using @ConditionalOnProperty, @Profile, or environment checks.

Enable via:

βœ… Summary

ConceptDetails
CommandLineRunnerRuns code after app startup using String[] args
ApplicationRunnerRuns code with structured ApplicationArguments
Registering runnersUse @Component or define as @Bean
Use casesDB seeding, background tasks, config check

Both CommandLineRunner and ApplicationRunner in Spring Boot are excellent tools for running logic after the Spring app has initialized β€” quick, elegant, and built right into the framework.

πŸ“˜ External References