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、添加依赖

        
            org.springframework.boot
            spring-boot-configuration-processor
            2.2.1.RELEASE
        

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

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

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

    @Autowired
    private LocatorConfig locatorConfig;

5、使用示例

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

6、读取结果

SpringBoot中读取yml中配置的list对象的配置项_第1张图片

你可能感兴趣的:(SpringBoot,spring,boot,list,后端)