spring boot读取项目参数配置

Updated on in 程序人生 with 0 views and 0 comments

1、简介

spring boot项目启动时可以配置一些参数,我们可以通过实现ApplicationRunner或CommandLineRunner接口,并重写run方法来获取这些配置,如果项目内定义了多个类实现了这两个类的话,通过@Order注解来指定他们的执行顺序。

spring boot项目可以在启动的时候指定项目运行参数,eg: java -jar --user=wenyl

2、ApplicationRunner

2.1、源码解析

ApplicationRunner的run方法参数是ApplicationArguments,内部共有五个方法

public interface ApplicationArguments {
	String[] getSourceArgs();
	Set<String> getOptionNames();
	boolean containsOption(String name);
	List<String> getOptionValues(String name);
	List<String> getNonOptionArgs();
}

我们添加启动参数如下

image.png

getSourceArgs()以空格为分隔符,获取所有配置,并且以字符串形式返回

image.png

getOptionNames()方法用于获取配置项(配置项以--开头)的名称,这个方法返回的值是set集合,应为一个配置项的值,可能是数组,需要分开定义但是name都是同一个

image.png

getOptionValues()方法用于获取配置项的值,返回的是一个数组,意味着我们可以给同一个配置项定义不同的值,如我们添加的name属性,定义了两个值

image.png

getNonOptionArgs()方法用于获取费配置项参数,在测试用的配置中,有个hello参数是没有--前缀的获取到的也只有它

image.png

2.2、案例

@Component
public class MessageApplicationRunner1 implements ApplicationRunner {


    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("开始加载");
        List<String> nonOptionArgs = args.getNonOptionArgs();
        Set<String> optionNames = args.getOptionNames();
        for(String optionName:optionNames){
            System.out.println("参数-"+optionName+"   值:"+ args.getOptionValues(optionName));
        }
        String[] sourceArgs = args.getSourceArgs();
        System.out.println("结束加载");
    }
}

3、CommandLineRunner

CommandLineRunner没有ApplicationRunner那么多操作,只是以空格为分隔,截取配置,2.1中同样的配置,获取情况如下

image.png

@Component
public class MessageApplicationRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println(args);
    }
}

4、ApplicationRunner和CommandLineRunner的区别

ApplicationRunner的run方法的参数是ApplicationArguments,而CommandLineRunner的run方法的参数是String类型

image.pngimage.png


标题:spring boot读取项目参数配置
作者:wenyl
地址:http://www.wenyoulong.com/articles/2021/09/27/1632708755896.html