簡體   English   中英

在 SpringBoot 中從 application.propeties 初始化 Map

[英]Initializing Map from application.propeties in SpringBoot

我想通過使用 Spring 的@Value Annotation 來初始化一個類字段。

類字段的類型為Map<String, List<String>>

我曾嘗試使用 Spring 的表達式語言,但我一定做錯了,因為它在加載 Spring 應用程序上下文時會引發以下錯誤:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'myConfig': 
Unsatisfied dependency expressed through field 'iWantToBeInitialized'; 
nested exception is org.springframework.beans.factory.BeanExpressionException: 
Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException: 
EL1041E: After parsing a valid expression, there is still more data in the expression: 'a'

這是MyConfig.java的代碼:

@Configuration
public class MyConfig {

    @Value("#{'${foo.bar.mymap}'}")
    Map<String, List<String>> iWantToBeInitialized;
    
}

這是application.properties的代碼:

foo.bar.mymap=${baz.bub.other:{'a-key':{'a-value'},'b-key':{'b1-value','b2-value'},'c-key':{'c1-value'}}}

看起來它開始解析a a-key的 a ,但它無法弄清楚從中解析映射。

我已經嘗試搜索並絆倒了幾個 Spring 機制,包括定義“自定義屬性的東西”,但我無法弄清楚如何將這些示例的解決方案外推到我的特定用例。

有人可以指出我正確的方向嗎?


更新1:

我已嘗試應用此解決方案

它導致以下異常:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'myConfig': 
Unsatisfied dependency expressed through field 'myMap'; nested exception is org.springframework.beans.factory.BeanExpressionException: 
Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: 
EL1008E: Property or field 'value1' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?

更新 2:

跟進更新 1 中提到的解決方案

我編輯了答案,它以我正在尋找的方式解決了問題。

這個表達對我有用:

populate.map.content={{key1: {'value1', 'value1'}, key2: {'value2', 'value2'}, key3: {'value3', 'value3'}}

日志顯示Map<String, List<String>> propertyname已正確初始化:

在此處輸入圖像描述

跟隨代碼代碼片段

@Component
@ConfigurationProperties(prefix = "xxx")
public class MyConfig {

   private Map<String, List<String>> iWantToBeInitialized;
    
}
application.yml
==================

xxx:
  iWantToBeInitialized:
    a-key:
      - a-value
    b-key:
      - b1-value
      - b2-value

暫無
暫無

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

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