Search code examples
javaspringyamlspring-el

Is it possible to read YAML property into Map using Spring and @Value annotation


What I want to be able to do is:

YAML:

features:
    feature1: true
    feature2: false
    feature3: true

Code:

@Value("${features}")
private Map<String,Boolean> features;

I can't figure out what Spring scripting syntax to use to do this (if it's possible at all)


Solution

  • I'm using Spring Boot and access custom variables like this:

    1. Create a custom class that maps to your custom properties:

      @Component
      @ConfigurationProperties(prefix="features")
      public class ConstantProperties {
          private String feature1;
      
          public String getFeature1(){
              return feature1;
          }
          public void setFeature1(String feature1) {
              this.feature1 = feature1;
          }
      }
      
    2. YAML file will look like this:

      features:
        feature1: true
        feature2: false
        feature3: true
      
    3. in your class that you want to access these properties, you can use the following:

      @Autowire 
      private ConfigurationProperties configurationProperties;
      
    4. Then to access in that class, use the following syntax:

      configurationProperties.getFeature1();
      
    5. Or you can reference the custom property like:

      "{{features.feature1}}"