新西兰服务器

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


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

发布时间:2022-02-23 09:07:36 来源:高防服务器网 阅读:90 作者:iii 栏目:开发技术

今天小编给大家分享一下SpringBoot怎么读取配置文件中的数据到map和list的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

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

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

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

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

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

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

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

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

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

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

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

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

package com.eknows.config;  import org.springframework.boot.context.properties.ConfigurationProperties;  import org.springframework.boot.context.properties.EnableConfigurationProperties;  import org.springframework.context.annotation.Configuration;  import java.util.HashMap;  import java.util.Map;  /**   * 配置类   * 从配置文件中读取数据映射到map   * 注意:必须实现set方法   * @author eknows   * @version 1.0   * @since 2019/2/13 9:23   */  Configuration  ConfigurationProperties(prefix = "test")  EnableConfigurationProperties(MapConfig.class)  public class MapConfig {      /**       * 从配置文件中读取的limitSizeMap开头的数据       * 注意:名称必须与配置文件中保持一致       */      private Map<String, Integer> limitSizeMap = new HashMap<>();      public Map<String, Integer> getLimitSizeMap() {          return limitSizeMap;      }      public void setLimitSizeMap(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依赖项。

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

package com.eknows.config;  import org.springframework.boot.context.properties.ConfigurationProperties;  import org.springframework.boot.context.properties.EnableConfigurationProperties;  import org.springframework.context.annotation.Configuration;  import java.util.ArrayList;  import java.util.List;  /**   * 配置类   * 从配置文件中读取数据映射到list   * @author eknows   * @version 1.0   * @since 2019/2/13 9:34   */  Configuration  @ConfigurationProperties(prefix = "test-list") // 不同的配置类,其前缀不能相同  @EnableConfigurationProperties(ListConfig.class) // 必须标明这个类是允许配置的  public class ListConfig {      private List<String> limitSizeList = new ArrayList<>();      public List<String> getLimitSizeList() {          return limitSizeList;      }      public void setLimitSizeList(List<String> limitSizeList) {          this.limitSizeList = limitSizeList;      }  }

测试上述配置是否有效

编写测试类:

package com.eknows;  import com.eknows.config.ListConfig;  import com.eknows.config.MapConfig;  import org.junit.Test;  import org.junit.runner.RunWith;  import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.boot.test.context.SpringBootTest;  import org.springframework.test.context.junit4.SpringRunner;  import java.util.List;  import java.util.Map;  /**   * @author eknows   * @version 1.0   * @since 2019/2/13 9:28   */  @SpringBootTest  @RunWith(SpringRunner.class)  public class ConfigTest {      @Autowired      private MapConfig mapConfig;      @Autowired      private ListConfig listConfig;      @Test      public void testMapConfig() {          Map<String, Integer> limitSizeMap = mapConfig.getLimitSizeMap();          if (limitSizeMap == null || limitSizeMap.size() <= 0) {              System.out.println("limitSizeMap读取失败");          } else {              System.out.println("limitSizeMap读取成功,数据如下:");              for (String key : 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 (String str : 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 = 8081  custom.name = lonewalker  custom.age = 18

第一种方式

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

import org.springframework.beans.factory.annotation.Value;  import org.springframework.stereotype.Component;   @Component  public class User {       @Value("${custom.name}")      private String name;       private Integer age;       public String getName() {          return name;      }         public void setName(String name) {          this.name = name;      }            public Integer getAge() {          return age;      }         @Value("${custom.age}")      public void setAge(Integer age) {          this.age = age;      }  }

我们在测试环境试一下:

@SpringBootTest  class DemoApplicationTests {       @Autowired      User user;       @Test      void contextLoads() {          System.out.println(user.getName());          System.out.println(user.getAge());      }   }

第二种方式

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

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

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

@Component  @ConfigurationProperties(prefix = "custom")  public class User {       private String name;       private Integer age;   getter()... setter()...  }

扩展

1、如何获取list数据

test.list=aaa,bbb,ccc

又该如何读取呢?

@SpringBootTest  class DemoApplicationTests {       @Value("#{'${test.list:}'.empty ? null : '${test.list:}'.split(',')}")      private List<String> testList;       @Test      void contextLoads() {        if (testList == null){            System.out.println("empty");        }else{            for (String list:testList                 ) {                System.out.println(list);            }        }      }   }

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

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

2、如何获取map数据

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

以上就是“SpringBoot怎么读取配置文件中的数据到map和list”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注高防服务器网行业资讯频道。

[微信提示:高防服务器能助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

[图文来源于网络,不代表本站立场,如有侵权,请联系高防服务器网删除]
[