CommandLineRunner并不是Spring框架原有的概念,它属于SpringBoot应用特定的回调扩展接口:

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,我们需要关注的点有两个:

  1. 所有CommandLineRunner的执行时间点是在SpringBoot应用的Application完全初始化工作之后(这里我们可以认为是SpringBoot应用启动类main方法执行完成之前的最后一步)。
  2. 当前SpringBoot应用的ApplicationContext中的所有CommandLinerRunner都会被加载执行(无论是手动注册还是被自动扫描注册到IoC容器中)。

  跟其他几个扩展点接口类型相似,我们建议CommandLineRunner的实现类使用@org.springframework.core.annotation.Order进行标注或者实现org.springframework.core.Ordered接口,便于对他们的执行顺序进行排序调整,这是非常有必要的,因为我们不希望不合适的CommandLineRunner实现类阻塞了后面其他CommandLineRunner的执行。这个接口非常有用和重要,我们需要重点关注。

二、如果扩展

在使用SpringBoot构建项目时,我们通常有一些预先数据的加载。那么SpringBoot提供了一个简单的方式来实现–CommandLineRunner。

1、在项目服务启动的时候就去加载一些数据到缓存或做一些事情这样的需求。

CommandLineRunner是一个接口,我们需要时,只需实现该接口就行。如果存在多个加载的数据,我们也可以使用@Order注解来排序。
案例:

加载数据库数据到缓存

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 <<<<<<<<<<<<<");
}
}

ApplicationRunner接口也可以实现上述功能

实现的方式类似的,如下:

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 <<<<<<<<<<<<<");
}
}

最新文章

  1. Expert 诊断优化系列------------------语句调优三板斧
  2. git 提交代码到github错误处理
  3. npm config
  4. Salesforce中所有常用类型字段的取值与赋值
  5. angularJS的$watch和$apply
  6. JS如何调用隐藏按钮的click事件
  7. WPF、Windows Forms和Silverlight间的联系和区别(转)
  8. linux软件的安装,更新与卸载
  9. java中string.trim()函数的使用
  10. Spring Boot 入门教程
  11. CXF 5参考资料
  12. 关于加载font-awesome文字显示不出来
  13. Docker &amp; ASP.NET Core (4):容器间的连接
  14. sqlserver 3145
  15. HDU 1175 连连看 (DFS+剪枝)
  16. 关于IOC和DI
  17. python自学——文件打开
  18. Linux 查看磁盘分区、文件系统、磁盘的使用情况相关的命令和工具介绍
  19. zookeeper 版本不一致导致不断重连
  20. Django模板层

热门文章

  1. doucment的获取节点的信息
  2. 某安全设备未授权访问+任意文件下载0day
  3. android Gradle下载慢,使用阿里镜像
  4. JavaScript的Proxy可以做哪些有意思的事儿
  5. 使用PSCI机制的SMP启动分析
  6. 搭建Ceph分布式存储
  7. Matplotlib 绘制定制的直方图
  8. 利用pandas映射替换两个字典中的映射值
  9. windows环境安装rabbitmq
  10. wp_list_categories()函数使用方法|wordpress函数