CommandLineRunner 系统启动任务

1.CommandLineRunner

MyCommandLineRunner.java

package com.zhuantai.commandlinerunner;

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

import java.util.Arrays;

/**
* 系统启动任务
* @author ANTIA1
* @date 2021/7/8 16:05
*/
@Component
@Order(100)//指定优先级,数字越小优先级越大
public class MyCommandLineRunner implements CommandLineRunner {
//当系统启动时,run方法会被触发,方法参数就是 main 方法所传入的参数
@Override
public void run(String... args) throws Exception {
System.out.println("args=" + Arrays.toString(args));

}
}


测试:

CommandLineRunner 系统启动任务_系统启动

运行结果:

CommandLineRunner 系统启动任务_系统启动_02

测试2:

D:\Project\spring-boot-demos\commandlinerunner\target>java -jar commandlinerunner-0.0.1-SNAPSHOT.jar 朱安泰 张三 李四


运行结果:

CommandLineRunner 系统启动任务_jar_03

2.ApplicationRunner

package com.zhuantai.commandlinerunner;

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

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
* @author ANTIA1
* @date 2021/7/8 19:22
*/
@Component
@Order(90)
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {

//获取没有key的参数,获取到的值和commandLineRunner一致
List<String> nonOptionArgs = args.getNonOptionArgs();
System.out.println("nonOptionArgs = " + nonOptionArgs);

//获取键值对参数
Set<String> optionNames = args.getOptionNames();
for (String optionName : optionNames) {
System.out.println(optionName+" = " + args.getOptionValues(optionName));
}

//获取命令行中的所有参数
String[] sourceArgs = args.getSourceArgs();
System.out.println("sourceArgs = " + Arrays.toString(sourceArgs));
}
}


运行结果:

CommandLineRunner 系统启动任务_jar_04