我们经常会有这样的需求,在Spring boot项目启动后需要马上执行一些任务,比如初始化的任务
实现的方法有很多中,今天我们介绍的是通过CommandLineRunner来实现
- 实现CommandLineRunner接口,然后添加@Component注解
- 然后在run方法中实现具体要运行的任务
- 如果有多个任务且有先后执行顺序,可用@Order注解,value值越小优先级越高
创建如下两个简单的任务,跑起来看看
@Component
@Order(value = 1) // 指定其执行顺序,值越小优先级越高
public class MyRunner1 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("MyRunner1");
}
}
@Component
@Order(value = 2) // 指定其执行顺序,值越小优先级越高
public class MyRunner2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("MyRunner2");
}
}
结果如下,两个任务在MyApplication启动后运行,且MyRunner1先运行
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 ''
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)
MyRunner1
MyRunner2