简体   繁体   English

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

[英]How get value from yaml file based on method param in spring?

I work with yaml and spring boot and I will make a method which will be validate my field. 我使用yaml和spring boot进行工作,我将制定一种方法来验证我的领域。

  1. If field value non null I have to return this value. 如果字段值非null,则必须返回该值。
  2. If field value null I have to load default value from yaml file based on fieldName. 如果字段值为null,则必须基于fieldName从yaml文件中加载默认值。

My method example: 我的方法示例:

@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 file: yaml文件:

values:
  field: defaultValue
  field1: defaultValue1
  field2: defaultValue2
  field3: defaultValue3

How can it be implemented in Spring boot + yaml? 如何在Spring Boot + Yaml中实现?

You can use YamlPropertiesFactoryBean to convert YAML to PropertySource. 您可以使用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;
        }
    }
}

And then use it like: 然后像这样使用它:

@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:blog.yaml")
public class YamlPropertysourceApplication {

You will find the whole description here: 您将在此处找到完整的描述:

https://mdeinum.github.io/2018-07-04-PropertySource-with-yaml-files/ https://mdeinum.github.io/2018-07-04-PropertySource-with-yaml-files/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM