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

Spring boot 通过ApplicationRunner在启动完成后按指定顺序执行任务
强烈推介IDEA2021.1.3破解激活,IntelliJ IDEA 注册码,2021.1.3IDEA 激活码  

大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说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. }

  8. }

 
  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

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18249

发表评论