ITPub博客

首页 > 应用开发 > > Spring Boot项目启动就想加载数据,或者启动服务怎么办?

Spring Boot项目启动就想加载数据,或者启动服务怎么办?

作者:jasonhsp 时间:2019-11-07 09:27:53 0 删除 编辑

介绍

实际应用中,我们会有在项目启动的时候就去加载一些数据或启动一些服务的需求。

我们可以通过实现Spring Boot中的CommandLineRunner接口来达成目的。

输出为

CommandLineRunner

main end

当有多个加载的操作,想把他们放到不同的类中(写多个CommandLineRunner的实现类),并想指定他们的启动顺序(用@Order注解),可以这样来写

@Component

@Order(value = 1)

public class StartupRunner1 implements CommandLineRunner {

@Override

public void run(String... args) throws Exception {

System.out.println("StartupRunner1");

}

}


@Component

@Order(value = 2)

public class StartupRunner2 implements CommandLineRunner {

@Override

public void run(String... args) throws Exception {

System.out.println("StartupRunner2");

}

}


@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

System.out.println("main end");

}

}

输出如下

StartupRunner1

StartupRunner2

main end

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/615/viewspace-3142101/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-12

  • 博文量
    342
  • 访问量
    2720