SpringBoot的ApplicationRunner和CommandLineRunner

如果你需要在你的SpringBoot启动完成之后实现一些功能,那么可以通过创建class实现ApplicationRunner和CommandLineRunner来完成:

@Component
public class ApplicationRunnerTest implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("========>> ApplicationRunner.run");
        for (String sourceArg : args.getSourceArgs()) {
            System.out.println(sourceArg);
        }
        for (String optionName : args.getOptionNames()) {
            System.out.println(optionName + " = " + args.getOptionValues(optionName));
        }
        System.out.println("========>> End");
    }
}
@Component
public class CommandLineRunnerTest implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("========>> CommandLineRunner.run");
        for (String sourceArg : args) {
            System.out.println(sourceArg);
        }
        System.out.println("========>> End");
    }
}

如果你定义了多个ApplicationRunner或者CommandLineRunner,并想要控制他们执行的先后顺序,可以让你定义的class实现org.springframework.core.Ordered接口,或者直接注解@Order

posted @ 2018-11-01 17:49  柚子苹果果  阅读(625)  评论(0编辑  收藏  举报