我使用yaml和spring boot,我将制作一种可以验证我的领域的方法。
我的方法示例:
@PropertySource("classpath:defaultValue.yml")
public final class ValidateAttributeValue {
public static String validateAttributeValue(String attributeName, String attributeValue){
if (nonNull(attributeValue)){
return attributeValue;
}
//here I have to return default value from file based on attributeName
}
yaml文件:
values:
field: defaultValue
field1: defaultValue1
field2: defaultValue2
field3: defaultValue3
如何在Spring boot + yaml中实现它?
答案 0 :(得分:1)
您可以使用YamlPropertiesFactoryBean
将YAML转换为PropertySource。
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
然后像这样使用它:
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:blog.yaml")
public class YamlPropertysourceApplication {
您将在此处找到整个说明:
https://mdeinum.github.io/2018-07-04-PropertySource-with-yaml-files/