有时候项目会有这样的需求:在 springboot 项目启动完成之后,需要加载一些数据
最先想到的方法就是通过 ApplicationRunner
去做:
@Component
public class TestApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("TestApplicationRunner method will be execute when the project started");
}
}
除了 ApplicationRunner
这种方式去做之外,还可以通过 CommandLineRunner
去做:
@Component
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("TestCommandLineRunner method will be execute when the project started");
}
}
上图是写了之后的运行效果图,应该可以看到,在项目启动成功之后,我们在 ApplicationRunner
和 CommandLineRunner
中的内容就运行了,而且执行顺序上, ApplicationRunner
要比 CommandLineRunner
先执行
这篇文章就先简单介绍一下 springboot 项目启动完成之后,如何执行特定方法,我在项目中用的第一种方式去实现的
如果想要让多个方法按照顺序执行,可以试下 @Order
实现方式:
@Component
public class TestApplicationRunnerByOrder implements ApplicationRunner, Ordered {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("TestApplicationRunnerByOrder method will be execute when the project started");
}
@Override
public int getOrder() {
// 通过设置这里的数字来指定执行顺序
return 0;
}
}
@Component
public class TestApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("TestApplicationRunner method will be execute when the project started");
}
}
如果是上面的代码的话,运行之后,程序执行结果是这样的:
如果我们在 TestApplicationRunner
方法上,加上 @Order(value = 0)
注解:
@Component
@Order(value = 0)
public class TestApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("TestApplicationRunner method will be execute when the project started");
}
}
接下来运行,就能看到执行顺序相比于刚刚,发生了变化:
以上,感谢您的阅读哇~