springboot使用CommandLineRunner解决项目启动时初始化资源的操作
前言:
在我们实际工作中,总会遇到这样需求,在项目启动的时候需要做一些初始化的操作,比如初始化线程池,提前加载好加密证书等。
今天就给大家介绍一个SpringBoot神器,专门帮助大家解决项目启动初始化资源操作。
这个神器就是CommandLineRunner,CommandLineRunner接口的Component会在所有SpringBeans都初始化之后,SpringApplication.run()之前执行,非常适合在应用程序启动之初进行一些数据初始化的工作。
正文:
接下来我们就运用案例测试它如何使用,在测试之前在启动类加两行打印提示,方便我们识别CommandLineRunner的执行时机。
@SpringBootApplication publicclassSpringbootRabbitmqApplication{ publicstaticvoidmain(String[]args){ System.out.println("Theservicetostart"); SpringApplication.run(SpringbootRabbitmqApplication.class,args); System.out.println("Theservicetostarted"); } }
接下来我们直接创建一个类继承CommandLineRunner,并实现它的run()方法。
@Component publicclassRunnerimplementsCommandLineRunner{ @Override publicvoidrun(String...args)throwsException{ System.out.println("TheRunnerstarttoinitialize..."); } }
启动项目进行测试:
... Theservicetostart. ._________ /\\/___'_____(_)______\\\\ (()\___|'_|'_||'_\/_`|\\\\ \\/___)||_)|||||||(_||)))) '|____|.__|_||_|_||_\__,|//// =========|_|==============|___/=/_/_/_/ ::SpringBoot::(v2.0.2.RELEASE) ... 2021-02-0111:38:31.314[main]INFOo.s.boot.web.embedded.tomcat.TomcatWebServer-Tomcatstartedonport(s):8078(http)withcontextpath'' 2021-02-0111:38:31.317[main]INFOcom.cn.SpringbootRabbitmqApplication-StartedSpringbootRabbitmqApplicationin4.124seconds(JVMrunningfor6.226) TheRunnerstarttoinitialize... Theservicetostarted
根据控制台的打印信息我们可以看出CommandLineRunner中的方法会在SpringBoot容器加载之后执行,执行完成后项目启动完成。
如果我们在启动容器的时候需要初始化很多资源,并且初始化资源相互之间有序,那如何保证不同的CommandLineRunner的执行顺序呢?SpringBoot也给出了解决方案。那就是使用@Order注解。
我们创建两个CommandLineRunner的实现类来进行测试:
第一个实现类:
@Component @Order(1) publicclassOrderRunner1implementsCommandLineRunner{ @Override publicvoidrun(String...args)throwsException{ System.out.println("TheOrderRunner1starttoinitialize..."); } }
第二个实现类:
@Component @Order(2) publicclassOrderRunner2implementsCommandLineRunner{ @Override publicvoidrun(String...args)throwsException{ System.out.println("TheOrderRunner2starttoinitialize..."); } }
添加完成之后重新启动,观察执行顺序:
... Theservicetostart. ._________ /\\/___'_____(_)______\\\\ (()\___|'_|'_||'_\/_`|\\\\ \\/___)||_)|||||||(_||)))) '|____|.__|_||_|_||_\__,|//// =========|_|==============|___/=/_/_/_/ ::SpringBoot::(v2.0.2.RELEASE) ... 2021-02-0111:42:05.724[main]INFOo.s.boot.web.embedded.tomcat.TomcatWebServer-Tomcatstartedonport(s):8078(http)withcontextpath'' 2021-02-0111:42:05.728[main]INFOcom.cn.SpringbootRabbitmqApplication-StartedSpringbootRabbitmqApplicationin3.472seconds(JVMrunningfor5.473) TheOrderRunner1starttoinitialize... TheOrderRunner2starttoinitialize... TheRunnerstarttoinitialize... Theservicetostarted
通过控制台的输出我们发现,添加@Order注解的实现类最先执行,并且@Order()里面的值越小启动越早。
在实践中,使用ApplicationRunner也可以达到相同的目的,两着差别不大。
以上就是springboot使用CommandLineRunner解决项目启动时初始化资源的操作的详细内容,更多关于springboot解决项目启动时初始化资源的操作的资料请关注毛票票其它相关文章!