SpringBoot读取Yml中基本数据类型、List、Map、数组数据

SpringBoot读取Yml中基本数据类型、List、Map、数组数据

目录

SpringBoot读取Yml中基本数据类型、List、Map、数组数据

1、概述        

2、读取基本数据类型

3.1、读取对象List

3.2、读取String的List集合

4、读取数组

5、 读取Map数据


1、概述        

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

pom文件需要添加依赖

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

2、读取基本数据类型

yml配置:

custom:
  string:
    value: test

代码实现:

使用@Value注解即可

@Value("${custom.string.value}")
private String stringValue;

结果:

3.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());
    }

结果:

3.2、读取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());
    }

结果:

4、读取数组

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));
    }

结果:

5、 读取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());
    }

结果:

  • 5
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值