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:



@FunctionalInterface
public interface CommandLineRunner {
    void run(String... args) throws Exception;
}

βœ… Example:



@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("CommandLineRunner: App just started!");
        for (String arg : args) {
            System.out.println("Arg: " + arg);
        }
    }
}

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

πŸ› οΈ 2. Using ApplicationRunner

πŸ“¦ Interface:



@FunctionalInterface
public interface ApplicationRunner {
    void run(ApplicationArguments args) throws Exception;
}

βœ… Example:



@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) {
        System.out.println("ApplicationRunner: App has started!");
        if (args.containsOption("user")) {
            System.out.println("User arg: " + args.getOptionValues("user"));
        }
    }
}

You can start your app like this:


java -jar app.jar --user=admin

And get output like:


User arg: [admin]

πŸ” 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:



@SpringBootApplication
public class DemoApp {

    public static void main(String[] args) {
        SpringApplication.run(DemoApp.class, args);
    }

    @Bean
    CommandLineRunner clr() {
        return args -> {
            System.out.println("CLR inside @Bean");
        };
    }

    @Bean
    ApplicationRunner ar() {
        return args -> {
            System.out.println("AR inside @Bean");
        };
    }
}

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


@Component
public class DataSeeder implements CommandLineRunner {
    private final UserRepository userRepository;

    public DataSeeder(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public void run(String... args) {
        userRepository.save(new User("admin", "admin@example.com"));
        System.out.println("Initial user created");
    }
}

βœ… 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:



@Component
@Order(1)
public class FirstRunner implements CommandLineRunner {
    public void run(String... args) {
        System.out.println("First Runner");
    }
}

@Component
@Order(2)
public class SecondRunner implements CommandLineRunner {
    public void run(String... args) {
        System.out.println("Second Runner");
    }
}

🧘 Optional: Conditional Execution

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


@Component
@ConditionalOnProperty(name = "app.seed-data", havingValue = "true")
public class DataSeeder implements CommandLineRunner {
    // ...
}

Enable via:



app.seed-data=true

βœ… 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