介绍
实际应用中,我们会有在项目启动的时候就去加载一些数据或启动一些服务的需求。
我们可以通过实现Spring Boot中的CommandLineRunner接口来达成目的。
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("main end");
}
@Override
public void run(String... args) throws Exception {
System.out.println("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