CommandLineRunner接口可以实现任务的自动加载,当项目启动完后,就会自动去执行CommandLineRunner接口里的run方法,你可以实现多个CommandLineRunner的实例,使用order来控制执行的顺序!
/**
* 项目启动后自动运行的代码CommandLineRunner
*/
@Component
@Order(1)
public class MyStartupRunner1 implements CommandLineRunner {
private Logger logger = LoggerFactory.getLogger(MyStartupRunner1.class);
@Override
public void run(String... args) throws Exception {
logger.info("MyStartupRunner1里的数据");
}
}
@Component
@Order(2)
public class MyStartupRunner2 implements CommandLineRunner {
private Logger logger = LoggerFactory.getLogger(MyStartupRunner1.class);
@Override
public void run(String... args) throws Exception {
logger.info("MyStartupRunner2里的数据");
}
}
程序在启动之后,可以看到控制台的日志,它们被执行了。
2020-05-26 10:25:07.400 INFO 27788 --- [ main] .d.s.w.r.o.CachingOperationNameGenerator : Generating unique operation named: getUsingGET_1
2020-05-26 10:25:07.433 INFO 27788 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-05-26 10:25:07.435 INFO 27788 --- [ main] com.lind.basic.BasicApplication : Started BasicApplication in 6.967 seconds (JVM running for 8.118)
2020-05-26 10:25:07.437 INFO 27788 --- [ main] com.lind.basic.init.MyStartupRunner1 : MyStartupRunner1里的数据
2020-05-26 10:25:07.437 INFO 27788 --- [ main] com.lind.basic.init.MyStartupRunner1 : MyStartupRunner2里的数据