springboot加载自定义yml并自动注入成对象

1.创建定义test.yml文件,下面是个复杂的Yml文件

report:
  reportList[0]:
    taskId: 4
    path: axxx
    rule[0]:
      type: PERSON_FREQ
      periodUnit: day
      numberOfSeparation: 2
      times: 2
    rule[1]:
      type: PERSON_MAX
      participants: 50
  reportList[1]:
    taskId: 3
    path: bxxxx
    rule:
      type: PERSON_MAX
      participants: 7

2. 创建实体对象
是读取 路径下,test.yml文件,并用自定义的工厂类解析注入。

@PropertySource(value = "classpath:test.yml", factory = YamlPropertyLoaderFactory.class)

ReportVo 的属性值是在yml的前缀,report下面的。

@ConfigurationProperties(prefix = "report")

实体类对象声明必须与yml上的名称一样

@Data
@Component
@PropertySource(value = "classpath:test.yml", factory = YamlPropertyLoaderFactory.class)
@ConfigurationProperties(prefix = "report")
public class ReportVO {

    private List<ReportInitVO> reportList;

}

3.加入 自定义的yml 资源加载工厂类

public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {


    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {

        if (null == resource) {
            super.createPropertySource(name, resource);
        }
        return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()).get(0);
    }

}

3.pom 文件加入依赖

  <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-configuration-processor</artifactId>
           <optional>true</optional>
 </dependency>

4.使用
直接注入 你定义的实体类即可

  @Autowired
    ReportVO vo;
    @Test
    public  void test33(){
        List<ReportInitVO> reportList = vo.getReportList();
        ReportInitVO reportInitVO = reportList.get(0);
        System.out.println(reportList.size());
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值