![](/img/trans.png)
[英]Initializing Service and Repository Classes in Springboot Application Class
[英]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 中提到的解決方案:
我編輯了答案,它以我正在尋找的方式解決了問題。
跟隨代碼代碼片段
@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.