The CommandLineRunner interface in springboot implements the function of executing custom code after startup

API of CommandLineRunner interface:

import org.springframework.core.annotation.Order;
public interface CommandLineRunner {
    
    
    /**
     * Callback used to run the bean.
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    void run(String... args) throws Exception;
}

In development, there are functions that need to be implemented after the project is started. A simple implementation solution provided by SpringBoot is to add a model and implement the CommandLineRunner interface. The code to implement the function is placed in the implemented run method.
The specific implementation is as follows:

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyStartupRunner implements CommandLineRunner{
    
    
    @Override
    public void run(String... args) throws Exception {
    
    
        System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作<<<<<<<<<<<<<");
    }
}

If there are multiple classes that implement the CommandLineRunner interface, how to ensure the order:
After the project starts, SpringBoot will traverse all the entity classes that implement CommandLineRunner and execute the run method. If you need to execute in a certain order, then you need to use an @ on the entity class Order annotation [@Order(value=1...)] (or implement the Order interface) to indicate the order.
Look at two examples:

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value=1)
public class MyStartupRunnerOne implements CommandLineRunner{
    
    
    @Override
    public void run(String... args) throws Exception {
    
    
        System.out.println(">>>>>>>>>>>>>>>服务启动第一个开始执行的任务,执行加载数据等操作<<<<<<<<<<<<<");
    }
}
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value=2)
public class MyStartupRunnerTwo implements CommandLineRunner{
    
    
    @Override
    public void run(String... args) throws Exception {
    
    
        System.out.println(">>>>>>>>>>>>>>>服务第二顺序启动执行,执行加载数据等操作<<<<<<<<<<<<<");
    }
}

The @order annotation is used to realize the definition of the loading and starting order of the above two examples.

Guess you like

Origin blog.csdn.net/u011930054/article/details/107034902