SpringBoot CommandLineRunner详解
简述
如果在项目中,我们想在项目启动的时候干一些事情,比如从数据库加载一些数据、提前加载加密证书,并且这些功能只干一次
我们就可以使用CommandLineRunner完成我们的需求,我们可以继承CommandLineRunner接口,实现其run方法
这样在springboot启动的时候会自动运行我们实现的run方法
普通地实现run方法
下面这个springboot启动类执行后就会调用run方法,run方法只执行一次
@SpringBootApplication public class CommandLineRunnerApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(CommandLineRunnerApplication.class, args); } @Override public void run(String... args) throws Exception { System.out.println("abc"); } }
根据springboot启动参数控制
其中的run方法的入参就是springboot启动的时候的参数,我们可以手动根据参数判断来干些什么事情
@SpringBootApplication public class CommandLineRunnerApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(CommandLineRunnerApplication.class, args); } @Override public void run(String... args) throws Exception { if (Objects.equals(args[0], "abc")) { System.out.println("foo bar"); } } }
多个CommandLineRunner的执行顺序
References
https://blog.csdn.net/chenlixiao007/article/details/113881768
https://developer.aliyun.com/article/897438
一点一点积累,一点一点蜕变!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言
2020-03-17 matlab初学第四课•Layton大讲堂之 matlab简单的判断流程控制
2019-03-17 第二章内容小结以及资料分享