温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2022-02-23 09:07:36 来源:亿速云 阅读:391 作者: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 的元素个数就不是空了

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

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

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

2、如何获取map数据

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

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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI