-1

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mefisto_Fell
  • 876
  • 1
  • 10
  • 30
  • 1
    You can autowire Environment and access them as shown similar to the answer to this question: https://stackoverflow.com/questions/23506471/spring-access-all-environment-properties-as-a-map-or-properties-object – Rob Scully May 29 '19 at 15:40
  • you cannot access yml file using `@PropertySource` – Ryuzaki L May 29 '19 at 16:10

1 Answers1

1

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/

Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82