在系统一开始加载的时候,需要初始化一些数据,例如文件的加载、数据库的初始化等操作,在spring 中 可以使用 Listener 进行解决,但是在spring boot 使用 CommandLineRunner 和 ApplicationRunner 来解决,两个类的用于基本一致,唯一不同的是参数
CommandLineRunner:Spring boot 在启动的时候,会遍历该类的实现类
在项目启动的时候,会遍历该类的实现类,并且 会调用里面的run 方法,如果是多个 CommandLineRunner 可以使用@Order 来进行优先级的顺序,数字越小,优先级越高
@Component
@Order(1)
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.err.println("MyCommadLineRunner >>> " + Arrays.toString(args));
}
}
程序的初始化参数设置
ApplicationRunner
@Component
@Order(3)
public class MyApplicationRunner1 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
List<String> nonOptionArgs = args.getNonOptionArgs();
System.err.println("MyApplicationRunner1 >> " +nonOptionArgs);
Set<String> optionNames = args.getOptionNames();
for (String optionName: optionNames) {
System.err.println("key:"+optionName+">>>value :"+ args.getOptionValues(optionName));
}
}
}