SpringBoot扩展点之二:ApplicationRunner和CommandLineRunner的扩展
2024-09-06 12:13:15
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,我们需要关注的点有两个:
- 所有CommandLineRunner的执行时间点是在SpringBoot应用的Application完全初始化工作之后(这里我们可以认为是SpringBoot应用启动类main方法执行完成之前的最后一步)。
- 当前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 <<<<<<<<<<<<<");
}
}
最新文章
- Expert 诊断优化系列------------------语句调优三板斧
- git 提交代码到github错误处理
- npm config
- Salesforce中所有常用类型字段的取值与赋值
- angularJS的$watch和$apply
- JS如何调用隐藏按钮的click事件
- WPF、Windows Forms和Silverlight间的联系和区别(转)
- linux软件的安装,更新与卸载
- java中string.trim()函数的使用
- Spring Boot 入门教程
- CXF 5参考资料
- 关于加载font-awesome文字显示不出来
- Docker &; ASP.NET Core (4):容器间的连接
- sqlserver 3145
- HDU 1175 连连看 (DFS+剪枝)
- 关于IOC和DI
- python自学——文件打开
- Linux 查看磁盘分区、文件系统、磁盘的使用情况相关的命令和工具介绍
- zookeeper 版本不一致导致不断重连
- Django模板层