Spring Boot
ApplicationRunner
CommandLineRunner
Java
Software Development

When and why do we need ApplicationRunner and Runner interface?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

ApplicationRunner and CommandLineRunner are Spring Boot hooks for running code after the application context is ready. They are useful for startup initialization tasks that require fully created beans. Choosing the right runner and keeping startup work controlled prevents slow or fragile application boot.

Startup Execution Lifecycle

Both runner types execute after Spring Boot has created the context and before the application is considered fully started for business traffic. That makes them suitable for one-time startup logic such as validating external dependencies or preloading reference data.

Use runners for deterministic startup tasks, not for long-running background loops.

CommandLineRunner Basics

CommandLineRunner gives raw string arguments.

java
1import org.springframework.boot.CommandLineRunner;
2import org.springframework.stereotype.Component;
3
4@Component
5public class SeedRunner implements CommandLineRunner {
6    @Override
7    public void run(String... args) {
8        System.out.println("Startup args count: " + args.length);
9    }
10}

It is simple and works well when argument parsing needs are minimal.

ApplicationRunner Basics

ApplicationRunner provides ApplicationArguments, which separates option arguments and non-option arguments.

java
1import org.springframework.boot.ApplicationArguments;
2import org.springframework.boot.ApplicationRunner;
3import org.springframework.stereotype.Component;
4
5@Component
6public class ImportRunner implements ApplicationRunner {
7    @Override
8    public void run(ApplicationArguments args) {
9        if (args.containsOption("seed")) {
10            System.out.println("Seed mode enabled");
11        }
12        System.out.println("Non-option args: " + args.getNonOptionArgs());
13    }
14}

Use this when startup behavior depends on structured command-line options.

When to Use Runners

Good use cases:

  • Seed lookup tables once at startup.
  • Perform schema or dependency sanity checks.
  • Warm small caches required for first request latency.
  • Trigger one-off import tasks based on startup flags.

Avoid runners for:

  • Long polling loops.
  • Heavy batch jobs that can be scheduled separately.
  • Logic that should run per request.

Ordering Multiple Runners

If multiple runners exist, define execution order explicitly.

java
1import org.springframework.core.annotation.Order;
2import org.springframework.stereotype.Component;
3import org.springframework.boot.CommandLineRunner;
4
5@Component
6@Order(1)
7class FirstRunner implements CommandLineRunner {
8    public void run(String... args) {
9        System.out.println("First runner");
10    }
11}
12
13@Component
14@Order(2)
15class SecondRunner implements CommandLineRunner {
16    public void run(String... args) {
17        System.out.println("Second runner");
18    }
19}

This prevents hidden startup dependencies between components.

Failure Behavior and Operational Impact

If a runner throws an exception, application startup usually fails. This can be desirable for hard preconditions, but dangerous for non-critical tasks.

Pattern:

  • Fail fast for critical checks.
  • Catch and log non-critical initialization errors.
  • Keep startup time bounded with explicit timeouts.

When startup reliability matters, move optional tasks to async jobs after readiness.

Testing Runner Logic

You can test runner behavior with @SpringBootTest and controlled arguments.

java
1import org.junit.jupiter.api.Test;
2import org.springframework.boot.test.context.SpringBootTest;
3
4@SpringBootTest(args = "--seed=true")
5class RunnerIT {
6    @Test
7    void contextLoadsWithSeedFlag() {
8    }
9}

For unit-level tests, keep runner logic thin and delegate work to services that are easier to test in isolation.

Conditional Runner Activation

Startup tasks often differ by environment. You can activate runners only when a property or profile is enabled.

java
1import org.springframework.boot.CommandLineRunner;
2import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
3import org.springframework.context.annotation.Bean;
4import org.springframework.context.annotation.Configuration;
5
6@Configuration
7class RunnerConfig {
8    @Bean
9    @ConditionalOnProperty(name = "app.seed.enabled", havingValue = "true")
10    CommandLineRunner conditionalSeed() {
11        return args -> System.out.println("Seeding enabled");
12    }
13}

This avoids accidental data setup in production while keeping local onboarding easy. It also gives operations teams explicit control over one-time startup behavior via configuration.

Keep startup logs explicit for each runner so operators can confirm whether tasks ran, skipped, or failed during deployment.

Common Pitfalls

  • Placing heavy, slow tasks in runners and delaying startup.
  • Ignoring ordering when multiple runners depend on shared state.
  • Using runners for recurring jobs instead of scheduler or queue workers.
  • Throwing unhandled exceptions for non-critical initialization tasks.
  • Mixing argument parsing logic across many runners without clear ownership.

Summary

  • CommandLineRunner and ApplicationRunner execute after Spring context initialization.
  • Use CommandLineRunner for simple raw args and ApplicationRunner for richer option parsing.
  • Keep runner tasks short, deterministic, and startup-focused.
  • Control order and failure strategy explicitly.
  • Delegate heavy or recurring work to dedicated background mechanisms.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.