springboot 系统启动时执行
有一些特殊的任务需要在系统启动时执行,例如配置文件加载、数据库初始化等操作。如果没有使用Spring Boot,这些问题可以在Listener中解决。Spring Boot对此提供了两种解决方案:CommandLineRunner和ApplicationRunner。CommandLineRunner和ApplicationRunner基本一致,差别主要体现在参数上。
CommandLineRunner
Spring Boot项目在启动时会遍历所有CommandLineRunner的实现类并调用其中的run方法,如果整个系统中有多个CommandLineRunner的实现类,那么可以使用@Order注解对这些实现类的调用顺序进行排序。
1 2 3 4 5 6 7 8 9 10 | @Component @Order ( 1 ) public class MyCommandLineRunner1 implements CommandLineRunner { @Override public void run(String... args) { System.out.println( "Runner1>>>" + Arrays.toString(args)); } } |
• @Order(1)注解用来描述CommandLineRunner的执行顺序,数字越小越先执行。
• run方法中是调用的核心逻辑,参数是系统启动时传入的参数,即入口类中main方法的参数(在调用SpringApplication.run方法时被传入Spring Boot项目中)。
ApplicationRunner
ApplicationRunner的用法和CommandLineRunner基本一致,区别主要体现在run方法的参数上。
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Component @Order ( 1 ) public class MyApplicationRunner1 implements ApplicationRunner { @Override public void run(ApplicationArguments args) { List<String> nonOptionArgs = args.getNonOptionArgs(); System.out.println( "1-nonOptionArgs>>>" + nonOptionArgs); Set<String> optionNames = args.getOptionNames(); for (String optionName : optionNames) { System.out.println( "1-key:" + optionName + ";value:" + args.getOptionValues(optionName)); } } } |
• @Order注解依然是用来描述执行顺序的,数字越小越优先执行。
• 不同于CommandLineRunner中run方法的String数组参数,这里run方法的参数是一个ApplicationArguments对象,如果想从ApplicationArguments对象中获取入口类中main方法接收的参数,调用ApplicationArguments中的getNonOptionArgs方法即可。ApplicationArguments中的getOptionNames方法用来获取项目启动命令行中参数的key,例如将本项目打成jar包,运行java -jar xxx.jar –name=xc命令来启动项目,此时getOptionNames方法获取到的就是name,而getOptionValues方法则是获取相应的value。
测试
jar启动
1 | java -jar xc-springboot- 0.0 . 2 -SNAPSHOT.jar --name=xc --age= 18 a1 a2 |
idea启动

结果:
参考文章: Spring Boot+Vue全栈开发实战 - 4.9 启动系统任务
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-04-12 idea mysqldump
2017-04-12 js 获取随机数 Math.random()