[SpringBoot15] Implementation of startup tasks in SpringBoot

We will use the project startup task in the project, that is, some things that need to be done when the project starts, such as: data initialization, obtaining third-party data, etc., so how to implement the startup task in SpringBoot, let’s take a look

Two project startup schemes are provided in SpringBoot, CommandLineRunner and ApplicationRunner
1. CommandLineRunner
uses CommandLineRunner and needs to customize a class area to implement the CommandLineRunner interface, for example:
 

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

/**
 * 项目启动任务类
 */
@Component
@Order(100)
public class StartTask implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {

    }
}

We first use @Component to register the class as a bean in the Spring container
and then use @Order(100) to indicate the priority of the startup task. The larger the value, the lower the priority.
Implement the CommandLineRunner interface and rewrite run() method, when the project starts, the run() method will be executed, and there are two ways to pass parameters in the run() method
1. Pass in parameters in IDEA

 2. Package the project. When starting the project, enter the following command:

java -jar demo-0.0.1-SNAPSHOT.jar hello world

 

Two, ApplicationRunner

The usage of ApplicationRunner and CommandLineRunner is basically the same, but the parameters received are different, and parameters in the form of key-value can be received, as follows:

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 项目启动任务类
 */
@Component
@Order(100)
public class StartTask implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {

    }
}

 About the parameter ApplicationArguments of the run method:

1. args.getNonOptionArgs(); can be used to obtain keyless parameters in the command line (same as CommandLineRunner)
2. args.getOptionNames(); can be used to obtain keys of all key/value parameters
3. args.getOptionValues (key)); You can get the value of the parameter in the form of key/value according to the key
4, args.getSourceArgs(); means to get all the parameters in the command line

Parameter passing method:
1. Pass in parameters in IDEA 

 

 2. Package the project. When starting the project, enter the following command:

java -jar demo-0.0.1-SNAPSHOT.jar hello world --name=xiaoming

The above are the two ways to implement the project startup task in SpringBoot. The usage is basically the same, mainly reflected in the difference in passing parameters.

Guess you like

Origin blog.csdn.net/wufaqidong1/article/details/129476175