1.CommandLineRunner

@Component
@Order(99)      // 数字越大优先级越高
public class MyCommandlineruner implements CommandLineRunner {
    @Override
    // 这里的参数是系统启动时传入的
    public void run(String... args) throws Exception {
        System.out.println("方法内写需要执行的内容");
    }
}

2.ApplicationRunner

@Component
@Order(99)
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("与CommandLineRunner不同的是传入的参数,这里传入的参数是个对象");
        String[] sourceArgs = args.getSourceArgs(); // 获取启动的**所有**参数
        System.out.println(Arrays.toString(sourceArgs));
        List<String> nonOptionArgs = args.getNonOptionArgs();   // 返回的参数与CommandLineRunner类似(无**--**)
        System.out.println(nonOptionArgs);
        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            System.out.println(optionName+":"+args.getOptionValues(optionName));
        }
    }
}

ps:两种方式可以共用,优先级设置一样。

Last modification:April 2nd, 2020 at 05:10 pm
If you think my article is useful to you, please feel free to appreciate