introduction
When developing Spring Boot applications, we often need to perform some initialization tasks after the application is started, such as loading initial data, connecting to external services, performing health checks, etc. Spring Boot providesCommandLineRunner
Interfaces make the implementation of these tasks very simple and intuitive. This article will discuss in depthCommandLineRunner
The principle of , and details how to use it in a real project through multiple examples.
What is CommandLineRunner?
CommandLineRunner
It is an interface provided by Spring Boot, which is used to perform some initialization operations after the application starts. By implementingCommandLineRunner
Interface, you can automatically execute a piece of code at a certain point after the application is started. This is very useful in scenarios such as database initialization, data loading, logging, etc.
Interface definition
CommandLineRunner
There is only one method for the interface:
public interface CommandLineRunner { void run(String... args) throws Exception; }
-
run
Method: This method is called after the application is started. -
String... args
: Command line parameter array. -
throws Exception
: Allow any exception to be thrown.
life cycle
CommandLineRunner
ofrun
The method is called in the following stages:
- Spring Boot application starts: When
()
When the method is called, Spring Boot starts the application. - Spring container initialization: Spring container (usually
ApplicationContext
) is initialized, and all beans are created and injected into dependencies. -
CommandLineRunner
Call: Spring Boot will look for all implementationsCommandLineRunner
Interface beans and call their beans in orderrun
method. - Application Ready: All
CommandLineRunner
ofrun
After the method is executed, the application enters the ready state.
How to use CommandLineRunner
Basic usage
Step 1: Create a Spring Boot application
First, make sure you have created a basic Spring Boot application. If you haven't created it, you can use Spring Initializr to quickly generate it.
Step 2: Create an implementationCommandLineRunner
Interface class
import ; import ; @Component public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { // Check whether there are command line parameters passed if ( > 0) { // Call the first method and pass the parameters methodOne(args[0]); // Call the second method and pass the parameters methodTwo(args[1]); } else { ("No command line arguments provided."); } } private void methodOne(String param) { ("Method One with param: " + param); } private void methodTwo(String param) { ("Method Two with param: " + param); } }
Step 3: Create the main class
Make sure there is one in your main classmain
Method to start the Spring Boot application.
import ; import ; @SpringBootApplication public class MyApp { public static void main(String[] args) { (, args); } }
Step 4: Run the application
You can pass parameters through the command line to run the application. For example:
java -jar arg1 arg2
Example 1: Database Initialization
Suppose we need to initialize the database table and insert some initial data at the start of the application.
Create a database initialization class
import ; import ; import ; import ; @Component public class DatabaseInitializer implements CommandLineRunner { @Autowired private JdbcTemplate jdbcTemplate; @Override public void run(String... args) throws Exception { // Create table ("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))"); // Insert initial data ("INSERT INTO users (name) VALUES (?)", "Alice"); ("INSERT INTO users (name) VALUES (?)", "Bob"); ("Database initialized successfully."); } }
Example 2: External Service Connection
Suppose we need to connect to an external service when the application starts and verify that the connection is successful.
Create an external service connection class
import ; import ; import ; @Component public class ExternalServiceConnector implements CommandLineRunner { @Value("${}") private String serviceUrl; @Override public void run(String... args) throws Exception { // Simulate connection to external services ("Connecting to external service at: " + serviceUrl); // The simulation connection is successful ("Connection successful."); } }
Example 3: Health Check
Suppose we need to perform a series of health checks when the application starts to ensure that all dependencies are available.
Create a health check
import ; import ; import ; @Component public class HealthChecker implements CommandLineRunner { @Autowired private DatabaseHealthCheck databaseHealthCheck; @Autowired private ExternalServiceHealthCheck externalServiceHealthCheck; @Override public void run(String... args) throws Exception { // Check the database health status if (!()) { throw new RuntimeException("Database health check failed."); } // Check the health status of external services if (!()) { throw new RuntimeException("External service health check failed."); } ("All health checks passed successfully."); } }
Example 4: Multitasking
Suppose we need to execute multiple tasks when the application starts and these tasks need to be executed in a specific order.
Create multipleCommandLineRunner
kind
import ; import ; import ; @Component @Order(1) public class FirstTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { ("Executing the first task."); } } @Component @Order(2) public class SecondTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { ("Executing the second task."); } }
Control the execution order
CommandLineRunner
The execution order can be implementedOrdered
Interface or use@Order
Annotations to control.
use@Order
Note
import ; import ; import ; @Component @Order(1) public class FirstTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { ("Executing the first task."); } } @Component @Order(2) public class SecondTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { ("Executing the second task."); } }
useOrdered
Interface
import ; import ; import ; @Component public class FirstTask implements CommandLineRunner, Ordered { @Override public void run(String... args) throws Exception { ("Executing the first task."); } @Override public int getOrder() { return 1; } } @Component public class SecondTask implements CommandLineRunner, Ordered { @Override public void run(String... args) throws Exception { ("Executing the second task."); } @Override public int getOrder() { return 2; } }
Exception handling
existrun
In the method, you can throw any exception. It is recommended to add appropriate exception handling logic to prevent the application from accidentally terminated by unhandled exceptions.
Example
import ; import ; @Component public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { try { // Execute initialization tasks initializeData(); } catch (Exception e) { // Log an exception and stop the application startup ("Initialization failed: " + ()); (1); } } private void initializeData() { // Simulate initialization tasks ("Initializing data..."); // Simulate exceptions throw new RuntimeException("Initialization failed."); } }
Dependency injection
You can implement itCommandLineRunner
Inject other Spring-managed beans into the class torun
Use them in the method.
Example
import ; import ; import ; @Component public class MyCommandLineRunner implements CommandLineRunner { @Autowired private MyService myService; @Override public void run(String... args) throws Exception { // Call service method (); } } @Component public class MyService { public void doSomething() { ("Doing something..."); } }
Command line parameters
CommandLineRunner
ofrun
Method to receive aString... args
Array of parameters, which are passed from the command line. You canrun
These parameters are processed in the method.
Example
import ; import ; @Component public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { if ( > 0) { for (String arg : args) { ("Received argument: " + arg); } } else { ("No command line arguments provided."); } } }
MultipleCommandLineRunner
Execution order
If there are multiple implementations in the applicationCommandLineRunner
The interface classes, Spring Boot will call them in orderrun
method. You can achieveOrdered
Interface or use@Order
Annotations to control the execution order of these classes.
Example
import ; import ; import ; @Component @Order(1) public class FirstTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { ("Executing the first task."); } } @Component @Order(2) public class SecondTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { ("Executing the second task."); } }
Other precautions
-
Exception handling:exist
run
In the method, you should add appropriate exception handling logic to prevent the application from accidentally terminated due to unhandled exceptions. -
Dependency injection: You can achieve
CommandLineRunner
Inject other Spring-managed beans into the class to inject them intorun
Use them in the method. - Command line parameters: Ensure that the passed command line parameters are formatted correctly to avoid failure of application startup due to parameter errors.
Summarize
CommandLineRunner
It is a very useful interface provided by Spring Boot, which can help you perform initialization tasks after the application is started. By implementingrun
Method, you can easily perform various initialization operations and pass necessary configuration information through command line parameters. This article details how to use it in a real project through multiple examplesCommandLineRunner
, I hope it will be helpful to you.
This is the article about the principles and usage example analysis of CommandLineRunner in Spring Boot. For more information about Spring Boot CommandLineRunner, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!