SpringBoot启动任务

SpringBoot启动任务

可以注入CommandLineRunner类及其实现类的Bean

Spring启动时会扫描到这些类,并执行其中的run方法

最简单的Demo,在启动类中注入CommandLineRunner

@SpringBootApplication
public class TacoCloudApplication {

    public static void main(String[] args) {
        SpringApplication.run(TacoCloudApplication.class, args);
    }

    @Bean
    public CommandLineRunner dataLoader(IngredientRepository repo) {
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                //初始化操作
            }
        };
    }
}

如果有多个启动任务,可以创建多个CommandLineRunner的子类
执行顺序由@Order指定,优先级是按value值从小到大顺序

posted @ 2020-06-14 18:04  浮梦  阅读(259)  评论(0编辑  收藏  举报