因为spring中PropertySource的默认实现是properties类型文件的解析。
可以实现一个解析yaml文件的工具类,实现PropertySourceFactory接口。
第一步:实现工具类
public class YamlPropertySourceFactory implements PropertySourceFactory {
/**
* PropertySourceFactory针对yml的实现类
* @param name
* @param resource
* @return
* @throws IOException
*/
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
return sources.get(0);
}
}
第二步,配置使用YamlPropertySourceFactory。
@Component
// 在PropertySource后添加factory指定使用自定义实现的YamlPropertySourceFactory解析yml
@PropertySource(value = {"classpath:youryaml.yml"}, factory = YamlPropertySourceFactory.class)
@ConfigurationProperties("yourproprety")