0
点赞
收藏
分享

微信扫一扫

Spring boot 通过ApplicationRunner在启动完成后按指定顺序执行任务


  • 实现ApplicationRunner接口,然后添加@Component注解
  • 然后在run方法中实现具体要运行的任务
  • 如果有多个任务且有先后执行顺序,可用@Order注解,value值越小优先级越高

创建如下两个简单的任务,跑起来看看


1. @Component
2. @Order(value = 1) // 指定其执行顺序,值越小优先级越高
3. public class MyRunner1 implements ApplicationRunner {
4. @Override
5. public void run(ApplicationArguments args) throws Exception {
6. System.out.println("MyRunner1");
7. }

 



1. @Component
2. @Order(value = 2) // 指定其执行顺序,值越小优先级越高
3. public class MyRunner2 implements ApplicationRunner {
4. @Override
5. public void run(ApplicationArguments args) throws Exception {
6. System.out.println("MyRunner2");
7. }
8. }

结果如下,两个任务在MyApplication启动后运行,且MyRunner1先运行


1. 2020-08-21 15:21:49.169 custom-logback INFO 19368 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 88888 (http) with context path ''
2. 2020-08-21 15:21:49.177 custom-logback INFO 19368 --- [ main] com.yeyuanxinyi.MyApplication : Started MyApplication in 14.903 seconds (JVM running for 19.368)
3. MyRunner1
4. MyRunner2

举报

相关推荐

0 条评论