SpringBoot怎么读取配置文件中的数据到map和list(list,map,springboot,开发技术)

时间:2024-05-04 19:23:18 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

读取配置文件中的数据到map和list

之前使用过@Value("${name}")来读取springboot配置文件中的配置信息,比如:

@Value("${server.port}")privateIntegerport;

后面遇到一个新问题,如果我要把配置文件中的一系列数据一下子读出来到同一个数据结构中怎么办呢?

比如说读取配置信息到map或者list

下面来讲述一下如何实现这个功能。

springboot读取配置文件中的配置信息到map

首先看配置文件要读到map中的信息:

test:limitSizeMap:baidu:1024sogou:90hauwei:4096qq:1024

接着我们需要再maven的pom.xml文件中添加如下依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency>

然后定义一个配置类,代码如下:

packagecom.eknows.config;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.boot.context.properties.EnableConfigurationProperties;importorg.springframework.context.annotation.Configuration;importjava.util.HashMap;importjava.util.Map;/***配置类*从配置文件中读取数据映射到map*注意:必须实现set方法*@authoreknows*@version1.0*@since2019/2/139:23*/ConfigurationConfigurationProperties(prefix="test")EnableConfigurationProperties(MapConfig.class)publicclassMapConfig{/***从配置文件中读取的limitSizeMap开头的数据*注意:名称必须与配置文件中保持一致*/privateMap<String,Integer>limitSizeMap=newHashMap<>();publicMap<String,Integer>getLimitSizeMap(){returnlimitSizeMap;}publicvoidsetLimitSizeMap(Map<String,Integer>limitSizeMap){this.limitSizeMap=limitSizeMap;}}

这样,我们就可以把配置文件中的数据以map形式读出来了,key就是配置信息最后一个后缀,value就是值。

测试代码请看文章最后。

springboot读取配置文件中的配置信息到list

首先看配置文件要读到list中的信息:

test-list:limitSizeList[0]:"baidu:1024"limitSizeList[1]:"sogou:90"limitSizeList[2]:"hauwei:4096"limitSizeList[3]:"qq:1024"

接着如上添加spring-boot-configuration-processor依赖项。

然后定义配置类,代码如下:

packagecom.eknows.config;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.boot.context.properties.EnableConfigurationProperties;importorg.springframework.context.annotation.Configuration;importjava.util.ArrayList;importjava.util.List;/***配置类*从配置文件中读取数据映射到list*@authoreknows*@version1.0*@since2019/2/139:34*/Configuration@ConfigurationProperties(prefix="test-list")//不同的配置类,其前缀不能相同@EnableConfigurationProperties(ListConfig.class)//必须标明这个类是允许配置的publicclassListConfig{privateList<String>limitSizeList=newArrayList<>();publicList<String>getLimitSizeList(){returnlimitSizeList;}publicvoidsetLimitSizeList(List<String>limitSizeList){this.limitSizeList=limitSizeList;}}

测试上述配置是否有效

编写测试类:

packagecom.eknows;importcom.eknows.config.ListConfig;importcom.eknows.config.MapConfig;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringRunner;importjava.util.List;importjava.util.Map;/***@authoreknows*@version1.0*@since2019/2/139:28*/@SpringBootTest@RunWith(SpringRunner.class)publicclassConfigTest{@AutowiredprivateMapConfigmapConfig;@AutowiredprivateListConfiglistConfig;@TestpublicvoidtestMapConfig(){Map<String,Integer>limitSizeMap=mapConfig.getLimitSizeMap();if(limitSizeMap==null||limitSizeMap.size()<=0){System.out.println("limitSizeMap读取失败");}else{System.out.println("limitSizeMap读取成功,数据如下:");for(Stringkey:limitSizeMap.keySet()){System.out.println("key:"+key+",value:"+limitSizeMap.get(key));}}System.out.println("------");List<String>limitSizeList=listConfig.getLimitSizeList();if(limitSizeList==null||limitSizeList.size()<=0){System.out.println("limitSizeList读取失败");}else{System.out.println("limitSizeList读取成功,数据如下:");for(Stringstr:limitSizeList){System.out.println(str);}}}}

运行测试类,发现控制台输出如下:

limitSizeMap读取成功,数据如下:
key: qq, value: 1024
key: baidu, value: 1024
key: sogou, value: 90
key: hauwei, value: 4096
------
limitSizeList读取成功,数据如下:
baidu: 1024
sogou: 90
hauwei: 4096
qq: 1024

配置文件的读取(包括list、map类型)

添加配置文件处理器的依赖,这样在编写配置文件的时候就会有提示了。

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><version>2.1.3.RELEASE</version></dependency>

有了依赖,可以直接使用application.properties文件为我们工作了,这是Springboot的默认文件,它会通过其机制读取到上下文中,这样就可以引用它了

读取配置文件

在使用maven项目中,配置文件会放在resources根目录下。

我们的springBoot是用Maven搭建的,所以springBoot的默认配置文件和自定义的配置文件都放在此目录。

springBoot的 默认配置文件为application.properties或application.yml,这里我们使用application.properties。

首先在application.properties中添加我们要读取的数据。

server.port=8081custom.name=lonewalkercustom.age=18

第一种方式

我们可以通过@Value注解,这是Spring就有的,使用${...}占位符来读取配置在属性文件中的内容,既可以加在属性也可以加在方法上

importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;@ComponentpublicclassUser{@Value("${custom.name}")privateStringname;privateIntegerage;publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicIntegergetAge(){returnage;}@Value("${custom.age}")publicvoidsetAge(Integerage){this.age=age;}}

我们在测试环境试一下:

@SpringBootTestclassDemoApplicationTests{@AutowiredUseruser;@TestvoidcontextLoads(){System.out.println(user.getName());System.out.println(user.getAge());}}

第二种方式

如果有很多我们就要写很多@Value,就会很麻烦,于是就有第二种方式

通过注解@ConfigurationProperties(prefix="配置文件中的key的前缀")可以将配置文件中的配置自动与实体进行映射,默认从全局配置文件中获取值。

@ConfigurationProperties("custom")这里的字符串database会和类中的属性名称组成全限定名去配置文件中查找

@Component@ConfigurationProperties(prefix="custom")publicclassUser{privateStringname;privateIntegerage;getter()...setter()...}

扩展

1、如何获取list数据

test.list=aaa,bbb,ccc

又该如何读取呢?

@SpringBootTestclassDemoApplicationTests{@Value("#{'${test.list:}'.empty?null:'${test.list:}'.split(',')}")privateList<String>testList;@TestvoidcontextLoads(){if(testList==null){System.out.println("empty");}else{for(Stringlist:testList){System.out.println(list);}}}}

首先这是一个EL表达式,${test.list:} 是为它加上默认值,但是这样有个问题,当不配置该 key 值,默认值会为空串,它的 length = 1,这样解析出来 list 的元素个数就不是空了

SpringBoot怎么读取配置文件中的数据到map和list

所以在此之前先判断一下是否为空,最终写成这样@Value("#{'${test.list:}'.empty ? null : '${test.list:}'.split(',')}") 就完美了,遍历的结果

SpringBoot怎么读取配置文件中的数据到map和list

2、如何获取map数据

test.map={name:"守约",force:"95"}

SpringBoot怎么读取配置文件中的数据到map和list

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:SpringBoot怎么读取配置文件中的数据到map和list的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:javascript中如何用Switch语句下一篇:

8 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18