2017-10-04 102 views
0

我希望能夠做的是:是否可以讀取YAML財產到使用Spring和@Value標註地圖

YAML:

features: 
    feature1: true 
    feature2: false 
    feature3: true 

代碼:

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

我無法弄清楚使用什麼Spring腳本語法來完成此操作(如果可能的話)

+1

[春季啓動的可能的複製 - 注入從application.yml映射](https://stackoverflow.com/questions/24917194/spring-boot-inject-map-from-application-yml) –

回答

0

我使用Spring Boot並訪問了客戶端m個變量是這樣的:

  1. 創建一個映射到您的自定義屬性的自定義類:

    @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文件看起來像這樣:

    features: 
        feature1: true 
        feature2: false 
        feature3: true 
    
  3. 你們班

    那要訪問這些屬性,可以使用以下內容:

    @Autowire 
    private ConfigurationProperties configurationProperties; 
    
  4. 然後給那個類的訪問,請使用以下語法:

    configurationProperties.getFeature1(); 
    
  5. 或者你可以引用自定義屬性,如:

    "{{features.feature1}}" 
    
相關問題