The 30 second answer
CommandLineRunner is for startup work that needs the initialized application context, such as warming a cache, seeding data or running a batch task. Spring Boot calls it after context refresh, when non-lazy singletons are initialized and the embedded server has started, but before ApplicationReadyEvent. It gets the raw command-line arguments; ApplicationRunner gets parsed arguments instead. If a runner throws an unhandled exception, startup fails and Spring Boot closes the context.
Spring Boot finds every runner bean, sorts them and calls each one:
String[] beanNames = beanFactory.getBeanNamesForType(Runner.class);
...
instancesToBeanNames.keySet().stream().sorted(comparator).forEach((runner) -> callRunner(runner, args));if (runner instanceof ApplicationRunner) {
callRunner(ApplicationRunner.class, runner, (applicationRunner) -> applicationRunner.run(args));
}
if (runner instanceof CommandLineRunner) {
callRunner(CommandLineRunner.class, runner,
(commandLineRunner) -> commandLineRunner.run(args.getSourceArgs()));
}SpringApplication.callRunners L755-L765 and callRunner L774-L782
Key facts from this code:
- Timing:
callRunnersis called inrun()afterrefreshContextandApplicationStartedEvent, and beforeApplicationReadyEvent. - Order: runners are sorted with the order comparator, so
@OrderorOrderedcontrols the sequence. Both runner types are sorted together. - Same thread: runners run on the main thread, one after another. A slow runner delays
ApplicationReadyEventand the readiness stateACCEPTING_TRAFFIC. - Failure: an exception is wrapped as
IllegalStateException("Failed to execute CommandLineRunner"), and startup fails.
Example:
@Component
@Order(1)
class CacheWarmup implements ApplicationRunner {
private final ProductCache cache;
CacheWarmup(ProductCache cache) { this.cache = cache; }
@Override
public void run(ApplicationArguments args) {
if (!args.containsOption("skip-warmup")) {
cache.loadTopProducts();
}
}
}Good uses: cache warm-up before readiness, checking that required external config exists, a CLI tool or batch job that runs and exits, seeding a local dev database.
Bad uses: long-running loops (they block the main thread and delay readiness) and schema migration (use Flyway or Liquibase, which Spring Boot runs earlier, during refresh).
**Runner vs. @EventListener(ApplicationReadyEvent.class):** runners run before readiness and can stop startup by failing. A ready-event listener runs after the app is marked ready; failures there do not prevent startup.
Sources (2)
- Spring Boot reference: Using the ApplicationRunner or CommandLineRunnerdocs.spring.io
- CommandLineRunner Javadocdocs.spring.io