繁体   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