![](/img/trans.png)
[英]unable to bind list of object properties from application.yml in spring
[英]spring application.yml reference list from another property
我有属性文件application-dev.yml
,内容如下:
spring.profiles: dev
config.some.value:
- ELEMENT1
- ELEMENT2
和另一个带有内容的application-staging.yml
:
spring.profiles: staging
config.some.value:
- ELEMENT1
- ELEMENT2
- ELEMENT3
所以我基本上不知道列表的大小。 当我在main application.yml
引用此列表时,如下所示:
some.value: ${config.some.value}
我Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'value'
。 如何正确引用它?
解
一种方法是在配置文件中使用以逗号分隔的列表:
spring.profiles: dev
config.some.value: ELEMENT1,ELEMENT2
spring.profiles: staging
config.some.value: ELEMENT1,ELEMENT2,ELEMENT3
然后你应该能够在application.yml中访问它
some.value: ${config.some.value}
此解决方案不需要预先知道列表大小。
说明
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配置属性binder会将该逗号分隔的字符串List<Strings>
转换为List<Strings>
。
MyProfile:
SomeValues:
- ELEMENT1
- ELEMENT2
-ELEMENT3
- ELEMENT4
---
MyProfile:
someValues:
- ELEMENT1
- ELEMENT2
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class YAMLConfig {
private List<String> SomeValues= new ArrayList<>();
// standard getters and setters
}
访问属性
@Autowired
private YAMLConfig myConfig;
private List<String> SomeValues= myConfig.SomeValues();
这对我有用
使用String数组时,第一个也是唯一的元素可以用逗号连接 - 最终结果与列表相同。 这意味着您可以像这样设置变量:
config.some.value:ELEMENT1,ELEMENT2,ELEMENT3
然后,在您的配置文件部分,您可以引用配置值,因为它是一个普通的字符串:
someValues:$ {config.some.value}
(我担心,)你必须像这样引用它:
application.yaml:
some.value:
-${config.some.value[0]}
-${config.some.value[1]}
-${config.some.value[2]}
......我预见到问题,当没有${config.some.value[2]}
(列表大小不一致...... - >解决方法:尝试“虚拟”/“noop”)。
参考文献:
这是使用多个值创建.yml文件的最佳方法:
spring:
profiles: dev
config:
some:
values: ELEMENT1,ELEMENT2
当我们使用.yml文件时,我们建议拆分每个单词。 要读取值,请使用:
@Value("${spring.config.some.values}")
private String[] values;
我希望它对你有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.