簡體   English   中英

是否可以使用 Spring 和 @Value 注釋將 YAML 屬性讀入 Map

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

我希望能夠做的是:

YAML:

features:
    feature1: true
    feature2: false
    feature3: true

代碼:

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

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

我正在使用 Spring Boot 並訪問這樣的自定義變量:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM