Springboot 读取配置文件中定义的数组集合,读取配置文件转为集合及配置文件特殊符号解析

一Springboot 读取配置文件中定义的数组集合,读取配置文件转为集合

一、定义配置文件
首先我们将数组配置信息,写入到配置文件中。这里使用核心配置文件或者自定义配置文件都可以,将自定义配置文件整合到核心文件中就行。配置文件如下:

register:
  numberinfo :
    - registerNumber: 1
      startTime: "08:00"
      endTime: "08:20"
    - registerNumber: 2
      startTime: "08:21"
      endTime: "08:40"
    - registerNumber: 3
      startTime: "08:41"
      endTime: "09:00"

注意这里:‘-’ 的作用,不知道的小伙伴可以看本文第二段,配置文件特殊符号解析。
二、创建对象

@Data
public class Numberinfo {
    private Integer registerNumber;
    private String startTime;
    private String endTime;
}

三、创建包装对象
上面我们将配置信息写入到配置文件中了,并且也定义单条数据抽象的对象;现在需要创建一个对象,用于将配置信息转化为抽象对象的列表。

@Component
@ConfigurationProperties(prefix="register")
public class NumberConfig {
    private List<Numberinfo>  numberinfo;
    public List<Numberinfo> getNumberinfo() {
        return numberinfo;
    }
    public void setNumberinfo(List<Numberinfo> numberinfo) {
        this.numberinfo = numberinfo;
    }
}

四、注意
1.ConfigurationProperties 注解用于设置Springboot从配置文件中取值过程中的约束。
2.定义的List 对象名应该和配置文件中的相同。numberinfo
3.Numberinfo 对象的属性名应该和配置文件中的key相同。

三、使用方法
在需要用到的类中通过注入该类就可以直接使用了

	@Autowired
    private NumberConfig numberConfig ;

二配置文件特殊符号解析

  • ’ # 表示注释
  • 对象
# conf.yml
animal: pets
hash: { name: Steve, foo: bar }

转换为 json 为:

{
    { "animal": "pets" },
    { "hash": { "name": "Steve", "foo": "bar" } }
}
  • 数组
# conf.yml
Animal:
 - Cat
 - Dog
 - Goldfish

转换为 json 为:

{ "Animal": [ "Cat", "Dog", "Goldfish" ] }
  • null
# conf.yml
parent: ~

.yml 中 ~ 表示 null,转换为 json 为:{ "parent": null }

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

焚目圣僧渡众生

你的 一角将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值