简体   繁体   中英

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.

  1. If field value non null I have to return this value.
  2. If field value null I have to load default value from yaml file based on fieldName.

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:

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

How can it be implemented in Spring boot + yaml?

You can use YamlPropertiesFactoryBean to convert YAML to 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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