springboot-CommandLineRunner-启动时执行任务
一、CommandLineRunner的作用
项目启动后,执行run方法中的代码。
如下所示:
package org.springboot.sample.runner; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class MyStartupRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作<<<<<<<<<<<<<"); } }
二、如果有多个类实现CommandLineRunner接口,如何保证顺序
使用@Order 注解,通过源码查看,order的值越小优先级越高
如下所示:
package org.springboot.sample.runner; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(value=2) public class MyStartupRunner1 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服务启动执行 2222 <<<<<<<<<<<<<"); } }
三、CommandLineRunner接口在SpringBoot启动时执行的顺序
CommandLineRunner接口的run()方法会在spring bean初始化之后,SpringApplication run之前执行,可以控制在项目启动前初始化资源文件,比如初始化线程池,提前加载好加密证书等
四、Springboot中的类似接口
ApplicationRunner
----------------------------------------------------------------------------
我的小鱼你醒了,
还认识早晨吗?
昨夜你曾经说,
愿夜幕永不开启。
你的香腮边轻轻滑落的,
是你的泪,还是我的泪?
初吻吻别的那个季节,
不是已经哭过了吗?
我的指尖还记忆着,
你慌乱的心跳。
温柔的体香里,
那一缕长发飘飘。