Java and Spring Level 1 This level · 81 of 105
Easy java spring

What is the real use of CommandLineRunner?

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.

Could you say this in an interview?

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: callRunners is called in run() after refreshContext and ApplicationStartedEvent, and before ApplicationReadyEvent.
  • Order: runners are sorted with the order comparator, so @Order or Ordered controls the sequence. Both runner types are sorted together.
  • Same thread: runners run on the main thread, one after another. A slow runner delays ApplicationReadyEvent and the readiness state ACCEPTING_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)
  1. Spring Boot reference: Using the ApplicationRunner or CommandLineRunnerdocs.spring.io
  2. CommandLineRunner Javadocdocs.spring.io
Previous
Next