我有属性文件application-dev.yml
,内容为:
spring.profiles: dev
config.some.value:
- ELEMENT1
- ELEMENT2
和另一个application-staging.yml
,内容为:
spring.profiles: staging
config.some.value:
- ELEMENT1
- ELEMENT2
- ELEMENT3
所以我基本上不知道列表的大小。当我在主 application.yml
中引用此列表时,如下所示:
some.value: ${config.some.value}
我得到无法将类型“java.lang.String”的属性值转换为属性“value”所需的类型“java.util.List”
。如何正确引用呢?
最佳答案
解决方案
一种方法是在您的个人资料中使用逗号分隔的列表:
- application-dev.yml
spring.profiles: dev
config.some.value: ELEMENT1,ELEMENT2
- application-staging.yml
spring.profiles: staging
config.some.value: ELEMENT1,ELEMENT2,ELEMENT3
然后您应该能够在 application.yml 中访问它
some.value: ${config.some.value}
此解决方案不需要预先了解列表大小。
说明
其起作用的原因已描述 here 。 具体来说:
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
这特别意味着,如果您在 application.yml
中指定以逗号分隔的字符串列表。并定义List<String>
作为 @ConfigurationProperties
中的值,spring 配置属性绑定(bind)器会将逗号分隔的字符串列表转换为 List<Strings>
.
关于来自另一个属性的 spring application.yml 引用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54366636/