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