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里的数据
总结
到此这篇关于springboot CommandLineRunner接口实现自动任务加载的文章就介绍到这了,更多相关spring boot CommandLineRunner现自动任务加载内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!
- 本文固定链接: https://zxbcw.cn/post/187392/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)