Spring Boot:Spring始终为属性分配默认值,尽管它存在于.properties文件中

Dar*_*hta 11 java spring spring-annotations spring-boot

我正在使用Spring 1.0.7,它使用Spring 4.0.7.我使用@Value注释在我的类中自动装配属性.如果属性文件中不存在该属性,我想要一个默认值,因此,我使用":"来指定默认值.以下是示例:

@Value("${custom.data.export:false}")
private boolean exportData = true;
Run Code Online (Sandbox Code Playgroud)

如果属性文件中不存在属性,则应该为变量赋值false.但是,如果文件中存在属性,那么它也会分配默认值并忽略属性值.例如,如果我定义了诸如上述应用属性文件中提到的一个属性有这样的事情custom.data.export=true的话,价值exportData仍然是假的,而应该是真正的理想.

谁能指导我在这里做错了什么?

谢谢

Oph*_*itz 12

我们被以下Spring bug咬了一下,症状完全相同:

[SPR-9989]使用多个PropertyPlaceholderConfigurer会破坏@Value默认值行为

基本上,如果PropertyPlaceholderConfigurerApplicationContext中存在多个单独的,则只会解析预定义的默认值,并且不会进行覆盖.设置不同的ignoreUnresolvablePlaceholders值对此事没有影响,一旦我们删除了额外的值,这两个值(真/假)在这方面同样有效PropertyPlaceholderConfigurer.

调查一下,每个定义的PropertyPlaceholderConfigurer内部都按预期解析了属性,但是Spring无法弄清楚要使用哪个属性来将值注入到带@Value注释的字段/参数中.


Arp*_*ain 5

您可以执行以下操作之一来克服此问题:

  1. 在配置器中使用自定义 valueSeparator

<bean id="customConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="location" value="file:${catalina.base}/conf/config2.properties"/>
     <property name="ignoreUnresolvablePlaceholders" value="true"/>
     <property name="valueSeparator" value="-defVal-"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

  1. 使用 order 属性增加相关配置器的偏好

<bean id="customConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="file:${catalina.base}/conf/config2.properties"/>
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
    <property name="order" value="-2147483648"/>
</bean?
Run Code Online (Sandbox Code Playgroud)

我在这个问题上做了一些研究,可在此处获得