In a Spring Boot application, sometimes you need to execute some logic right after the application starts.
Spring Boot provides two interfaces for this purpose:
CommandLineRunnerApplicationRunnerBoth are executed after the Spring ApplicationContext is fully loaded.
Application Starts
↓
Spring Context Initialization
↓
Beans Created & Dependencies Injected
↓
CommandLineRunner / ApplicationRunner Executed
↓
Application Ready
CommandLineRunner is a functional interface provided by Spring Boot.
@FunctionalInterface
public interface CommandLineRunner {
void run(String... args) throws Exception;
}
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Application started successfully!");
for (String arg : args) {
System.out.println("Argument: " + arg);
}
}
}
@Component
public class DataLoader implements CommandLineRunner {
private final UserRepository userRepository;
public DataLoader(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public void run(String... args) {
userRepository.save(new User("Admin", "admin@example.com"));
System.out.println("Default user created");
}
}
@FunctionalInterface
public interface ApplicationRunner {
void run(ApplicationArguments args) throws Exception;
}
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner executed");
if (args.containsOption("name")) {
System.out.println("Name: " + args.getOptionValues("name"));
}
System.out.println("Non-option args: " + args.getNonOptionArgs());
}
}
| Feature | CommandLineRunner | ApplicationRunner |
|---|---|---|
| Argument Type | String... args | ApplicationArguments |
| Structured Parsing | No | Yes |
| Access Option Names | No | Yes |
| Access Non-option Args | No | Yes |
@Component
@Order(1)
public class FirstRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("First Runner");
}
}
1. Creates ApplicationContext 2. Loads all Beans 3. Identifies CommandLineRunner & ApplicationRunner 4. Sorts them (if ordered) 5. Executes run() method
| Use Case | Recommended |
|---|---|
| Simple startup task | CommandLineRunner |
| Argument-based startup | ApplicationRunner |