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
• --name=xc --age=18都属于getOptionNames/getOptionValues范畴。
• 后面的 a1 a2 可以通过getNonOptionArgs方法获取,获取到的是一个数组,相当于上文提到的运行时配置的ProgramArguments。
 

idea启动

 结果:

 

 

参考文章: Spring Boot+Vue全栈开发实战 - 4.9 启动系统任务

posted @   草木物语  阅读(898)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-04-12 idea mysqldump
2017-04-12 js 获取随机数 Math.random()
点击右上角即可分享
微信分享提示