因为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")
本文介绍了如何在Spring中实现YamlPropertySourceFactory,以支持从YAML文件读取配置。首先创建了一个工具类,继承PropertySourceFactory并实现了createPropertySource方法,用于加载YAML文件。接着,通过在@PropertySource注解中指定factory参数,使用自定义的YamlPropertySourceFactory来解析配置。这种方法扩展了Spring默认的.properties文件解析能力。
2301

被折叠的 条评论
为什么被折叠?



