CommandLineRunner is a Spring Boot interface that allows developers to execute custom code immediately after the application has started and the Spring context has been fully initialized. It is commonly used for startup tasks such as loading initial data, validating configurations, creating default records, or performing initialization logic.
Why Do We Need CommandLineRunner?
Some applications need to perform actions immediately after startup.
CommandLineRunner provides a simple way to execute such logic automatically.
How Does It Work?
Application Starts
|
Spring Context Loaded
|
Beans Created
|
CommandLineRunner Executes
|
Application Ready
The run() method is called automatically after the application startup process completes.
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class StartupRunner
implements CommandLineRunner {
@Override
public void run(String... args)
throws Exception {
System.out.println(
"Application Started Successfully");
}
}Application Started Successfully
Accessing Command-Line Arguments
CommandLineRunner receives startup arguments through a String array.
@Component
public class StartupRunner
implements CommandLineRunner {
@Override
public void run(String... args) {
for (String arg : args) {
System.out.println(arg);
}
}
}java -jar app.jar prod test
prod
testCommon Use Cases
Suppose an e-commerce application needs product categories loaded into memory.
This improves application performance.
CommandLineRunner vs ApplicationRunner
Both execute after application startup.
CommandLineRunner
public void run(
String... args)
ApplicationRunner
public void run(
ApplicationArguments args)
java -jar app.jar --env=prod
env=prod
using ApplicationArguments.
--env=prod
as a String value.
Executing Multiple Runners
Execution order can be controlled using @Order.
@Component
@Order(1)
public class FirstRunner
implements CommandLineRunner {
}
@Component
@Order(2)
public class SecondRunner
implements CommandLineRunner {
}FirstRunner
↓
SecondRunner
Benefits of CommandLineRunner
Real-World Example
CommandLineRunner can perform these tasks automatically before the application begins serving requests.
A concise interview answer is
CommandLineRunner is a Spring Boot interface used to execute custom code immediately after the application starts and the Spring context is fully initialized. It is commonly used for startup tasks such as data initialization, cache loading, and configuration validation. The run() method receives command-line arguments as a String array and executes automatically during application startup.
Last updated: 11 November 2026
Previous question: What is ApplicationRunner in Spring Boot?
Next question: What is the Spring Boot CLI, and what are its most-used commands?