Spring Boot:Spring始终为属性分配默认值,即使它存在于.properties文件中 [英] Spring Boot : Spring always assigns default value to property despite of it being present in .properties file
问题描述
我正在使用使用Spring 4.0.7的Spring Boot 1.1.8.我使用@Value注释自动装配类中的属性.如果属性文件中不存在该属性,我希望有一个默认值,因此,我使用:"来分配默认值.下面是示例:
@Value("${custom.data.export:false}")
private boolean exportData = true;
如果在属性文件中不存在属性,则应为变量赋false.但是,如果文件中存在 if 属性,则它还会分配默认值,而忽略该属性值.
例如.如果我已经定义了上述属性,并且应用程序属性文件具有类似custom.data.export=true
的内容,那么exportData
的值将 still 为false,而理想情况下应为true.>
有人可以指导我在这里做错什么吗?
谢谢
我们被以下具有完全相同症状的Spring bug所咬伤:
[SPR-9989]使用多个PropertyPlaceholderConfigurer会破坏@Value默认值行为 >
基本上,如果ApplicationContext中存在多个PropertyPlaceholderConfigurer
,则仅解析预定义的默认值,并且不会发生替代.设置一个不同的ignoreUnresolvablePlaceholders
值对该问题没有影响,并且一旦我们删除了额外的PropertyPlaceholderConfigurer
,这两个值(对/错)在这方面同样有效.
仔细研究一下,每个定义的PropertyPlaceholderConfigurer
在内部都按预期解析了属性,但是Spring无法找出要使用哪个属性将值注入@Value
带注释的字段/参数中./p>
I am working with Spring boot 1.1.8 which uses Spring 4.0.7. I am autowiring the properties in my classes with @Value annotation. I want to have a default value if the property is not present in properties file so, I use ":" to assign default value. Below is the example:
@Value("${custom.data.export:false}")
private boolean exportData = true;
It should assign false to the variable if property is not present in the properties file which is does. However, if property is present in the file, then also it assigns default value and ignores the properties value.
E.g. if I have defined the property like the one mentioned above and application properties file has something like this custom.data.export=true
then, the value of exportData
will still be false whereas it should be true ideally.
Can anyone please guide me what I am doing wrong here?
Thanks
We were bitten by the following Spring bug with exactly the same symptom:
[SPR-9989] Using multiple PropertyPlaceholderConfigurer breaks @Value default value behavior
Basically if more than a single PropertyPlaceholderConfigurer
is present in the ApplicationContext, only predefined defaults will be resolved and no overrides will take place. Setting a different ignoreUnresolvablePlaceholders
value had no impact on the matter, and both values (true/false) worked equally well in that regard once we removed the extra PropertyPlaceholderConfigurer
.
Looking into it, each of the defined PropertyPlaceholderConfigurer
internally resolved the properties as expected, but Spring couldn't figure out which of them to use in order to inject a value into the @Value
annotated fields/params.
这篇关于Spring Boot:Spring始终为属性分配默认值,即使它存在于.properties文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!