![](/img/trans.png)
[英]Spring boot - Default properties file not being read when using profile
[英]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。 但是,如果文件中存在屬性,那么它也會分配默認值並忽略屬性值。 例如,如果我像上面提到的那樣定義了屬性,並且應用程序屬性文件有這樣的內容custom.data.export=true
那么, exportData
的值仍然是假的,而理想情況下應該是真。
誰能指導我我在這里做錯了什么?
謝謝
我們被以下具有相同症狀的Spring bug所咬傷:
[SPR-9989]使用多個PropertyPlaceholderConfigurer會破壞@Value默認值行為
基本上,如果ApplicationContext中存在多個PropertyPlaceholderConfigurer
,則僅解析預定義的默認值,並且不會發生任何替代。 設置一個不同的ignoreUnresolvablePlaceholders
值對此問題沒有影響,並且一旦我們刪除了額外的PropertyPlaceholderConfigurer
,這兩個值(true / false)在這方面都可以很好地工作。
仔細研究一下,每個定義的PropertyPlaceholderConfigurer
內部都按預期解析了屬性,但是Spring無法弄清楚要使用哪個屬性將值注入@Value
注釋字段/參數中。
您可以執行以下任一操作來克服此問題:
<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>
<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?
我已經在此問題上做了一些RnD, 可在此處找到 。
正如@Ophir Radnitz所說,這是一個Spring錯誤,當ApplicationContext中存在多個PropertyPlaceholderConfigurer時,就會發生此錯誤。
解決方法是,您可以通過以下方式獲得所需的行為:
(...)
@Autowired
private Environment environment;
(...)
private Boolean shouldExportData()
{
return environment.getProperty( "custom.data.export", Boolean.class, Boolean.FALSE );
}
發生這種情況,取決於參數的類型。
為String
參數設置默認值時,您的示例代碼作為默認值( @Value("${custom.string:test}")
)工作正常,對於其他類型(如boolean
,在您的問題中),默認值應該這樣寫:
@Value("${custom.data.export:#{true}}")
private boolean exportData = true;
類似地,對於Integers
:
@Value("${custom.integer:#{20}}")
祝你好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.