春天如何基于方法参数从yaml文件中获取价值?

时间:2019-05-29 15:09:29

标签: java spring spring-boot yaml

我使用yaml和spring boot,我将制作一种可以验证我的领域的方法。

  1. 如果字段值非null,则必须返回此值。
  2. 如果字段值null,则必须基于fieldName从yaml文件中加载默认值。

我的方法示例:

@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中实现它?

1 个答案:

答案 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/