Spring boot integrates WEB Development -- start task system

Keywords: Java Spring Database SpringBoot

Introduction:

There are some special tasks that need to be performed when the system starts, such as the loading of configuration files, database initialization and other operations. If spring boot is not used, these problems can be solved in the Listener. Spring boot provides two solutions: CommandLineRunner and ApplicationRunner. The two differences are mainly reflected in the parameters.

1.CommandLineRunner

The SpringBoot project will traverse all the CommandLineRunner implementation classes and invoke the run method when it starts. If there are multiple CommandLineRunner implementations in the whole system, @Order can be used to solve the sequential call sequence. The smaller the number, the more it will be called first.

Test:

@Component
@Order(1)
public class MyCommandLineRunner1 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("Runner1>>>"+Arrays.toString(args));
    }
}



@Component
@Order(2)
public class MyCommandLineRunner2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("Runner2>>>"+Arrays.toString(args));
    }
}

Parameter passed in at system startup, @ Order("1") precedes @ Order("2")

 

 

2.ApplicationRunner

The usage is basically the same as commandlinerunner. The difference lies in the parameters of the run method.

@Component
@Order(2)
public class MyApplicationRunner1 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
//Get the parameters accepted in the main method List
<String> nonOptionArgs = args.getNonOptionArgs(); System.out.println("1-nonOptionArgs>>>" + nonOptionArgs); //Get the parameter key in the project startup command line
Set
<String> optionNames = args.getOptionNames(); for (String optionName : optionNames) { System.out.println("1-key:" + optionName + ";value:" + //Corresponding value
args.getOptionValues(optionName)); } } } @Component @Order(
1) public class MyApplicationRunner2 implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { List<String> nonOptionArgs = args.getNonOptionArgs(); System.out.println("2-nonOptionArgs>>>" + nonOptionArgs); Set<String> optionNames = args.getOptionNames(); for (String optionName : optionNames) { System.out.println("2-key:" + optionName + ";value:" + args.getOptionValues(optionName)); } } }

 

Enter the file of the project: mvn package

 

Enter the target folder, find the jar we packed, and pass in the parameters

 

 

Posted by LucienFB on Wed, 19 Feb 2020 06:36:46 -0800