SpringBoot中读取yml中配置的list对象的配置项

场景

SpringBoot中通过ConfigurationProperties注解的方式读取application.yml中配置的属性值:

SpringBoot中通过ConfigurationProperties注解的方式读取application.yml中配置的属性值_demoenabled: true-CSDN博客

参考上面获取yml配置文件中简单的配置项的方式。

如果需要获取application.yml中配置的list数据,且每个list有多个属性的内容,比如下面添加在application.yml中的内容

locators:
  locatorList:
    - id: 0
      slaveId: 1
      offset: 0
    - id: 1
      slaveId: 1
      offset: 1
    - id: 2
      slaveId: 1
      offset: 2

可以通过如下方式实现。

注:

博客:
霸道流氓气质_C#,架构之路,SpringBoot-CSDN博客

实现

1、添加依赖

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

2、新建一个实体类,字段与配置文件中list的每个对象属性相同

import lombok.Data;

@Data
public class Locator {
    private Integer id;
    private Integer slaveId;
    private Integer offset;
}

3、新建一个配置类,添加注解

import com.badao.demo.entity.Locator;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
@Data
@ConfigurationProperties(prefix = "locators")
public class LocatorConfig {
    private List<Locator> locatorList;
}

前缀与配置文件中一致,属性名与配置文件中前缀下面的一致。

4、在需要使用该配置类的地方注入

    @Autowired
    private LocatorConfig locatorConfig;

5、使用示例

        BatchRead<Integer> batch = new BatchRead<>();
        List<Locator> locatorList = locatorConfig.getLocatorList();
        locatorList.forEach(locator -> batch.addLocator(locator.getId(), BaseLocator.coilStatus(locator.getSlaveId(),locator.getOffset())));

6、读取结果

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值