来自另一个属性的 spring application.yml 引用列表

Mat*_*usz 9 spring spring-properties

我有application-dev.yml包含内容的属性文件:

spring.profiles: dev
config.some.value:
- ELEMENT1
- ELEMENT2
Run Code Online (Sandbox Code Playgroud)

另一个application-staging.yml内容:

spring.profiles: staging
config.some.value:
- ELEMENT1
- ELEMENT2
- ELEMENT3
Run Code Online (Sandbox Code Playgroud)

所以我基本上不知道列表的大小。当我application.yml像这样在 main 中引用这个列表时:

some.value: ${config.some.value}
Run Code Online (Sandbox Code Playgroud)

我明白了Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'value'。如何正确引用?

Ole*_*kyi 10

解决方案

一种方法是在您的配置文件中使用逗号分隔的列表:

  • 应用程序-dev.yml
spring.profiles: dev
config.some.value: ELEMENT1,ELEMENT2
Run Code Online (Sandbox Code Playgroud)
  • application-staging.yml
spring.profiles: staging
config.some.value: ELEMENT1,ELEMENT2,ELEMENT3
Run Code Online (Sandbox Code Playgroud)

然后你应该可以在 application.yml 中访问它

some.value: ${config.some.value}
Run Code Online (Sandbox Code Playgroud)

此解决方案不需要预先知道列表大小。

解释

此处描述了此操作的原因。具体来说:

YAML lists are represented as comma-separated values (useful for simple String values) and also as property keys with [index] dereferencers, for example this YAML:
servers:
    - dev.bar.com
    - foo.bar.com
Would be transformed into these properties:
servers=dev.bar.com,foo.bar.com
servers[0]=dev.bar.com
servers[1]=foo.bar.com
Run Code Online (Sandbox Code Playgroud)

特别是这意味着,如果您指定以逗号分隔的字符串列表 inapplication.yml并定义List<String>为值 in @ConfigurationProperties,则 spring 配置属性绑定器会将逗号分隔的字符串列表转换为List<Strings>.