簡體   English   中英

當屬性不存在時,Spring @Value注釋不使用默認值

[英]Spring @Value annotation not using defaults when property is not present

我試圖在構造函數的參數中使用@Value注釋,如下所示:

@Autowired
public StringEncryptor(
    @Value("${encryptor.password:\"\"}") String password,
    @Value("${encryptor.algorithm:\"PBEWithMD5AndTripleDES\"}") String algorithm,
    @Value("${encryptor.poolSize:10}") Integer poolSize, 
    @Value("${encryptor.salt:\"\"}") String salt) {
...
}

當類路徑中存在屬性文件時,屬性將完美加載並且測試執行正常。 但是,當我從類路徑中刪除屬性文件時,我原本期望使用默認值,例如poolSize將設置為10或算法設置為PBEWithMD5AndTripleDES但是情況並非如此。

通過調試器運行代碼(只有在更改@Value("${encryptor.poolSize:10}") Integer poolSize后才能工作@Value("${encryptor.poolSize:10}") Integer poolSize@Value("${encryptor.poolSize:10}") String poolSize因為它導致NumberFormatExceptions)我發現沒有設置默認值,參數的形式為:

poolSize = ${encryptor.poolSize:10}

algorithm = ${encryptor.algorithm:"PBEWithMD5AndTripleDES"}

而不是預期的

poolSize = 10

algorithm = "PBEWithMD5AndTripleDES"

基於SPR-4785 ,$ {my.property:myDefaultValue}等符號應該有效。 但它並沒有發生在我身上!

謝謝

由於遺漏屬性文件,屬性占位符配置器的初始化可能會失敗,因此不會解析占位符。 您可以將其配置為忽略丟失的文件,如下所示(如果使用context命名空間進行配置):

<context:property-placeholder ignore-resource-not-found="true" ... />

此外,您不需要圍繞默認值"..."

ignore-resource-not-found =“true”不需要拾取默認值。 如果在任何地方找不到屬性,則指定默認值的點是使用它。

我認為上一個答案中的最后一句話指的是問題 - 你必須最初提供的錯誤的EL,但后來從示例中刪除了。 您獲得格式轉換異常的事實也指向了這一點。 通常,Spring會自動將字符串轉換為適當的“標准”Java類型,如果您提供自己的Spring轉換服務實現,也可以自定義您的自定義對象 - 只要您的轉換服務在應用程序上下文中定義。

當您通過XML注入屬性而沒有默認值時,“ignore-resource-not-found”非常有用,並且如果沒有找到屬性,則不希望容器拋出實例化bean的異常。 在這種情況下,bean屬性將使用Java默認值進行初始化,例如,對象為null,原始數值為0,等等。

在我的例子中,解析屬性值(和默認值)在測試中不起作用,我使用基於注釋的配置。 事實證明,我必須添加一個PropertySourcesPlaceholderConfigurer以便實際解析屬性。 它在PropertySource Annotation JavaDoc中進行了解釋:

為了使用PropertySource中的屬性解析定義中的$ {...}占位符或@Value注釋, 必須注冊PropertySourcesPlaceholderConfigurer 在XML中使用時會自動發生這種情況,但在使用@Configuration類時必須使用靜態@Bean方法顯式注冊。 有關詳細信息和示例,請參閱@Configuration Javadoc的“使用外部化值”部分和@Bean Javadoc的“關於BeanFactoryPostProcessor返回@Bean方法的說明”部分。

以下是訣竅:

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

如果您想添加單個屬性:

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {

    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();

    Properties properties = new Properties();
    properties.put("batchSize", "250");
    propertySourcesPlaceholderConfigurer.setProperties(properties);

    return propertySourcesPlaceholderConfigurer;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM