1. 概述
    在实际项目开发过程中,经常需要读取yml或者properties配置的数据,以yml配置文件为例,接下来将演示如何读取基本数据类型、List、Map、数组数据。
    pom文件需要添加依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <version>2.3.7.RELEASE</version>
    </dependency>
    
  2. 读取基本数据类型
    yml配置:
custom:
 string:
  value: test
 

代码实现:
使用@Value注解即可

@Value("${custom.string.value}")
private String stringValue;
  1. 读取对象List

yml配置

custom:
  beanlist:
    value:
      - name: 张三
        age: 18
      - name: 李四
        age: 20
      - name: 王五
        age: 22

这里需要注意的是,定义list集合不能用@value注解来获取list集合的值,需要定义一个配置类bean,然后使用@ConfigurationProperties注解来获取list集合值,做法如下:

User实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User{
    public String name;
    public Integer age;
}

配置类

@Data
@Component
@ConfigurationProperties(prefix = "custom.beanlist")
public class CustomBeanListConfig {
    List<User> value;
}

用法

@Autowired
private CustomBeanListConfig customBeanListConfig;
 
public void test() {
    System.out.println("读取对象List:" + customBeanListConfig.getValue());
}
  1. 读取String的List集合

yml配置

custom:
  list:
    value:
      - 1
      - 2
      - 3

定义配置bean使用@ConfigurationProperties注解获取对象集合值。

创建配置类

@Data
@Component
@ConfigurationProperties(prefix = "custom.list")
public class CustomListConfig {
 
    List<String> value;
}

用法:

@Autowired
private CustomListConfig customListConfig;
 
public void test() {
    System.out.println("读取List:" + customListConfig.getValue());
}
  1. 读取数组

yml配置

custom:
  array:
    value: 1,2,3

用法:

@Value("${custom.array.value}")
private String[] arrayValue;
 
public void test() {
        System.out.println("读取数组:");
        Arrays.stream(arrayValue).forEach(s -> System.out.println(s));
    }
  1. 读取Map数据

yml配置

custom:
  map:
    value: {name: 张三,age: 99}

定义配置bean使用@ConfigurationProperties注解获取对象集合值。

创建配置类

@Data
@Component
@ConfigurationProperties(prefix = "custom.map")
public class CustomMapConfig {
    Map<String,String> value;
}

用法:

 @Autowired
    private CustomMapConfig customMapConfig;
 
    public void test() {
        System.out.println("读取Map:");
        System.out.println(customMapConfig.toString());
    }

最后修改:2023 年 02 月 21 日
如果觉得我的文章对你有用,请随意赞赏