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

浪尽此生 提交于 2019-12-08 00:25:55

问题


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)


回答1:


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}}"
    


来源:https://stackoverflow.com/questions/46574149/is-it-possible-to-read-yaml-property-into-map-using-spring-and-value-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!