有一些特殊的任务需要在系统启动时执行,例如配置文件加载、数据库初始化等操作。SpringBoot对此提供了两种解决方案CommandLineRunner和ApplicationRunner。
方式一:CommandLineRunner
@Component
@Order(1)
public class CommandLineRunner1 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner1启动:"+Arrays.toString(args));
}
}
@Component
@Order(2)
public class CommandLineRunner2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner2启动:"+Arrays.toString(args));
}
}
@Order数字越小越先执行,参数args就是系统启动时main带过来的参数
方式二:ApplicationRunner
@Component
@Order(3)
public class ApplicationRunner3 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
List<String> nonOptionArgs = args.getNonOptionArgs();
System.out.println("ApplicationRunner3启动:"+nonOptionArgs);
Set<String> optionNames = args.getOptionNames();
for (String optionName : optionNames) {
System.out.println("key:"+optionName+",value:"+args.getOptionValues(optionName));
}
}
}