SoFunction
Updated on 2025-04-18

Analysis of the principle and usage examples of CommandLineRunner in Spring Boot

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 providesCommandLineRunnerInterfaces make the implementation of these tasks very simple and intuitive. This article will discuss in depthCommandLineRunnerThe principle of , and details how to use it in a real project through multiple examples.

What is CommandLineRunner?

CommandLineRunnerIt is an interface provided by Spring Boot, which is used to perform some initialization operations after the application starts. By implementingCommandLineRunnerInterface, 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

CommandLineRunnerThere is only one method for the interface:

public interface CommandLineRunner {
    void run(String... args) throws Exception;
}
  • runMethod: 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

CommandLineRunnerofrunThe 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 (usuallyApplicationContext) is initialized, and all beans are created and injected into dependencies.
  • CommandLineRunnerCall: Spring Boot will look for all implementationsCommandLineRunnerInterface beans and call their beans in orderrunmethod.
  • Application Ready: AllCommandLineRunnerofrunAfter 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 implementationCommandLineRunnerInterface 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 classmainMethod 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 multipleCommandLineRunnerkind

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

CommandLineRunnerThe execution order can be implementedOrderedInterface or use@OrderAnnotations to control.

use@OrderNote

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.");
    }
}

useOrderedInterface

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

existrunIn 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 itCommandLineRunnerInject other Spring-managed beans into the class torunUse 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

CommandLineRunnerofrunMethod to receive aString... argsArray of parameters, which are passed from the command line. You canrunThese 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.");
        }
    }
}

MultipleCommandLineRunnerExecution order

If there are multiple implementations in the applicationCommandLineRunnerThe interface classes, Spring Boot will call them in orderrunmethod. You can achieveOrderedInterface or use@OrderAnnotations 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:existrunIn the method, you should add appropriate exception handling logic to prevent the application from accidentally terminated due to unhandled exceptions.
  • Dependency injection: You can achieveCommandLineRunnerInject other Spring-managed beans into the class to inject them intorunUse 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

CommandLineRunnerIt is a very useful interface provided by Spring Boot, which can help you perform initialization tasks after the application is started. By implementingrunMethod, 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!