What is CommandLineRunner in Spring Boot?
CommandLineRunner is a functional interface provided by Spring Boot that allows developers to execute custom logic immediately after the Spring Boot application starts successfully.
It is mainly used to run startup code such as:
- Loading initial data into the database
- Executing startup scripts
- Testing database connections
- Printing application information
- Running scheduled initialization tasks
- Creating default admin users or roles
- Validating configurations during startup
In simple words, CommandLineRunner helps execute Java code automatically when the Spring Boot application is fully started.
Why is CommandLineRunner Used?
In many real-world applications, developers need to execute some logic immediately after the application starts.
Examples:
- Insert default records into the database
- Create admin users automatically
- Initialize cache data
- Print environment details
- Trigger startup validation checks
- Load interview questions or course data from files
Instead of manually triggering these tasks, Spring Boot provides CommandLineRunner to automate them.
How CommandLineRunner Works Internally
When a Spring Boot application starts:
- Spring Boot initializes the application context
- All beans are created and dependencies are injected
- The embedded server starts successfully
- Spring Boot searches for CommandLineRunner beans
- The
run()method gets executed automatically
This means CommandLineRunner runs only after the application is completely ready.
CommandLineRunner Interface
The CommandLineRunner interface belongs to:
org.springframework.boot.CommandLineRunner
It contains only one method:
void run(String... args) throws Exception;
Basic Example of CommandLineRunner
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");
System.out.println("Running startup logic...");
}
}
When the Spring Boot application starts, the output will automatically appear in the console.
Output
Application Started Successfully
Running startup logic...
Real-Time Example in Banking Application
Suppose you are building a banking application using Spring Boot.
Every time the application starts, you want to:
- Create default admin users
- Insert bank branch details
- Load interest rates into memory
- Validate payment gateway configuration
You can use CommandLineRunner for this purpose.
@Component
public class BankStartupRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("Loading bank configurations...");
System.out.println("Creating default admin account...");
System.out.println("Interest rates initialized...");
}
}
Using CommandLineRunner to Insert Data into Database
One of the most common uses of CommandLineRunner is inserting default data into the database.
Example: Insert Default Roles
@Component
public class RoleDataLoader implements CommandLineRunner {
private final RoleRepository roleRepository;
public RoleDataLoader(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
@Override
public void run(String... args) {
if(roleRepository.count() == 0) {
roleRepository.save(new Role("ADMIN"));
roleRepository.save(new Role("USER"));
System.out.println("Default roles inserted");
}
}
}
This automatically inserts default roles when the application starts for the first time.
Using Application Arguments in CommandLineRunner
CommandLineRunner can read startup arguments passed while running the application.
Example
@Component
public class ArgumentRunner implements CommandLineRunner {
@Override
public void run(String... args) {
for(String arg : args) {
System.out.println(arg);
}
}
}
Running the Application with Arguments
java -jar app.jar springboot java mysql
Output
springboot
java
mysql
Using Multiple CommandLineRunner Classes
A Spring Boot application can contain multiple CommandLineRunner implementations.
Spring Boot executes all CommandLineRunner beans during startup.
Example
@Component
public class FirstRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("First Runner Executed");
}
}
@Component
public class SecondRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("Second Runner Executed");
}
}
Controlling Execution Order
If multiple CommandLineRunner beans exist, execution order can be controlled using
the @Order annotation.
Example
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(1)
public class FirstRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("Executed First");
}
}
@Component
@Order(2)
public class SecondRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("Executed Second");
}
}
Output
Executed First
Executed Second
Difference Between CommandLineRunner and ApplicationRunner
| Feature | CommandLineRunner | ApplicationRunner |
|---|---|---|
| Arguments Type | String[] args | ApplicationArguments |
| Ease of Use | Simple | Advanced argument handling |
| Best For | Basic startup tasks | Complex startup arguments |
CommandLineRunner vs @PostConstruct
| Feature | CommandLineRunner | @PostConstruct |
|---|---|---|
| Runs After Application Startup | Yes | No |
| Application Context Fully Ready | Yes | Not Always |
| Supports Startup Arguments | Yes | No |
| Common Usage | Startup logic | Bean initialization |
Advantages of CommandLineRunner
- Automatically runs startup logic
- Useful for database initialization
- Supports startup arguments
- Easy to implement
- Works well with Spring Boot lifecycle
- Helps automate repetitive startup tasks
- Improves development efficiency
Disadvantages of CommandLineRunner
- Long-running tasks can slow application startup
- Improper database logic may cause startup failures
- Not suitable for heavy background processing
- Multiple runners may create confusion without ordering
Best Practices for Using CommandLineRunner
- Keep startup logic lightweight
- Avoid heavy processing inside run()
- Use @Order for multiple runners
- Use transactions for database operations
- Handle exceptions properly
- Do not place business logic directly inside runners
- Use services instead of writing all code inside run()
Production-Level Example
@Component
@Order(1)
public class StartupDataLoader implements CommandLineRunner {
private final UserService userService;
public StartupDataLoader(UserService userService) {
this.userService = userService;
}
@Override
public void run(String... args) {
userService.createDefaultAdmin();
System.out.println("Startup initialization completed");
}
}
In real enterprise applications, CommandLineRunner is commonly used for:
- Microservice initialization
- Default configuration loading
- Security setup
- Role creation
- Cache warming
- API key validation
- Environment checks
Common Interview Questions on CommandLineRunner
What is CommandLineRunner in Spring Boot?
CommandLineRunner is an interface in Spring Boot used to execute custom startup logic after the application context is fully loaded.
When does CommandLineRunner execute?
It executes immediately after the Spring Boot application starts successfully.
Can we have multiple CommandLineRunner implementations?
Yes. Multiple CommandLineRunner beans can exist, and their execution order can be controlled using the @Order annotation.
What is the difference between CommandLineRunner and ApplicationRunner?
CommandLineRunner uses simple String arguments, while ApplicationRunner provides advanced argument handling using ApplicationArguments.
Can CommandLineRunner be used in production applications?
Yes. It is widely used in production applications for startup initialization tasks, data loading, validation, and configuration setup.
Conclusion
CommandLineRunner is one of the most useful startup interfaces in Spring Boot. It helps developers execute custom initialization logic automatically after the application starts.
It is commonly used for database initialization, startup validation, loading default data, creating admin users, and configuring enterprise applications.
Understanding CommandLineRunner is important for Spring Boot developers because it is frequently used in real-world projects, microservices, enterprise systems, and technical interviews.