SpringBoot读取指定YML配置文件含配置对象集合

1、创建配置文件
application-county-contour.yml

contour:
  zoom: 12
  param-infos:
    -
      area_code: 350602000000
      left_down: 117.492954,24.484256
      right_up: 117.721185,24.69892
    -
      area_code: 350603000000
      left_down: 117.668088,24.477902
      right_up: 117.817736,24.605452
    -
      area_code: 350622000000
      left_down: 117.13006,23.751794
      right_up: 117.534442,24.229888

2、编写代码
这里使用到了@PropertySource注解,这个注解默认是不支持加载YML文件,所以需要重写一下


public class YamlConfigFactory extends DefaultPropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = name != null ? name : resource.getResource().getFilename();
        if (!resource.getResource().exists()) {
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }

    private Properties loadYml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}

然后在使用@PropertySource注解时指定我们自定义的类

@PropertySource(value = "classpath:application-county-contour.yml",factory = YamlConfigFactory.class)

这样就可以加载YML文件了,同时还可以配合@ConfigurationProperties注解使用,用来指定前缀
编写实体(对象列表)

@Data
public class CountyContourParam {

    private String areaCode;
    private String leftDown;
    private String rightUp;

}

编写外部配置对象

@Configuration
@PropertySource(value = "classpath:application-county-contour.yml",factory = YamlConfigFactory.class)
@ConfigurationProperties(prefix = "contour")
@Data
public class CountyContourConfig {
    private String zoom;
    List<CountyContourParam> paramInfos;


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值