CommandLineRunner并非Spring框架原有的概念,它属于SpringBoot应用特定的回调扩展接口:spring
public interface CommandLineRunner { /** * Callback used to run the bean. * @param args incoming main method arguments * @throws Exception on error */ void run(String... args) throws Exception; }
关于CommandLineRunner,咱们须要关注的点有两个:数据库
跟其余几个扩展点接口类型类似,咱们建议CommandLineRunner的实现类使用@org.springframework.core.annotation.Order进行标注或者实现org.springframework.core.Ordered
接口,便于对他们的执行顺序进行排序调整,这是很是有必要的,由于咱们不但愿不合适的CommandLineRunner实现类阻塞了后面其余CommandLineRunner的执行。这个接口很是有用和重要,咱们须要重点关注。缓存
在使用SpringBoot构建项目时,咱们一般有一些预先数据的加载。那么SpringBoot提供了一个简单的方式来实现–CommandLineRunner。框架
一、在项目服务启动的时候就去加载一些数据到缓存或作一些事情这样的需求。ide
CommandLineRunner是一个接口,咱们须要时,只需实现该接口就行。若是存在多个加载的数据,咱们也可使用@Order注解来排序。
案例:spa
加载数据库数据到缓存3d
package com.transsnet.palmpay.controller; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; //@Component @Order(value = 1) public class MyStartupRunner2 implements CommandLineRunner { @Override public void run(String... strings) throws Exception { System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操做 MyStartupRunner2 order 1 <<<<<<<<<<<<<"); } }
实现的方式相似的,以下:code
package com.transsnet.palmpay.controller; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(value = -1) public class MyStartupRunner3 implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操做 MyStartupRunner3 order -1 <<<<<<<<<<<<<"); } }