启动系统任务

​ SpringBoot对于系统启动时执行的任务,例如配置文件加载,数据库初始化等操作提供了两种解决方案:CommandLineRunner和ApplicationRunner,两者差别主要在于参数。
​ SpringBoot项目启动时会遍历所有的CommandLineRunner和ApplicationRunner的实现类并调用其中的run方法@Order注解可对于这些实现类调用顺序进行排序

  1. CommandLineRunner的实现类Demo

    /** * @author wsyjlly * @create 2019.06.14 - 19:36 * 配置启动系统参数 **/@Component@Order(1)public class MyCommandLineRunner1 implements CommandLineRunner {    @Override    public void run(String... args) throws Exception {        System.out.println("MyCommandLineRunner1:"+Arrays.toString(args));        System.out.println("——————————————————————");    }}
    /** * @author wsyjlly * @create 2019.06.14 - 19:36 * 配置启动系统参数 **/@Component@Order(2)public class MyCommandLineRunner2 implements CommandLineRunner {    @Override    public void run(String... args) throws Exception {        System.out.println("MyCommandLineRunner2:"+Arrays.toString(args));        System.out.println("——————————————————————");    }}
  1. ApplicationRunner的实现类Demo

    /** * @author wsyjlly * @create 2019.06.14 - 19:39 * 配置启动系统参数 **/@Component@Order(1)public class MyApplicationRunner1 implements ApplicationRunner {    @Override    public void run(ApplicationArguments args) throws Exception {        List<String> nonOptionArgs = args.getNonOptionArgs();        System.out.println("1-nonOptionArgs:"+nonOptionArgs);        Set<String> optionNames = args.getOptionNames();        for (String item:optionNames){            System.out.println("1-Key:"+item+";value:"+args.getOptionValues(item));        }    }}
    /** * @author wsyjlly * @create 2019.06.14 - 19:39 * 配置启动系统参数 **/@Component@Order(2)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 item:optionNames){            System.out.println("2-Key:"+item+";value:"+args.getOptionValues(item));        }    }}
  2. 测试

    • 测试参数
      测试参数
    • 打印结果
      打印结果
收藏 打印