2

鑑於有無法解決的佔位符某些應用程序配置,如下所示application.yml未解決的佔位符驗證春季啓動配置屬性

my: 
    thing: ${missing-placeholder}/whatever 

當我使用@Value註解,在配置文件中的佔位符進行驗證,所以在這種情況下, :

package com.test; 

import org.springframework.beans.factory.annotation.Value; 
import org.springframework.stereotype.Component; 

@Component 
public class PropValues { 
    @Value("${my.thing}") String thing; 
    public String getThing() { return thing; } 
} 

我收到IllegalArgumentException: Could not resolve placeholder 'missing-placeholder' in value "${missing-placeholder}/whatever"。這是因爲該值被直接設置由AbstractBeanFactory.resolveEmbeddedValue並沒有什麼追上通過PropertyPlaceholderHelper.parseStringValue

然而拋出的異常,尋找移動到@ConfigurationProperties風格我注意到,這驗證缺失,例如在這種情況下:

package com.test; 

import org.springframework.boot.context.properties.ConfigurationProperties; 
import org.springframework.validation.annotation.Validated; 

@ConfigurationProperties(prefix = "my") 
public class Props { 
    private String thing; 
    public String getThing() { return thing; }  
    public void setThing(String thing) { this.thing = thing; } 
} 

沒有例外。我可以看到PropertySourcesPropertyValues.getEnumerableProperty通過評論// Probably could not resolve placeholders, ignore it here捕獲異常,並將無效值收集到其內部映射中。後續的數據綁定不檢查未解決的佔位符。

我檢查過,只是將@Validated@Valid註釋應用於類和字段沒有幫助。

有沒有什麼辦法來保留在未解決的佔位符上拋出異常並使用ConfigurationProperties綁定的行爲?

+1

你應該,但'@ Validated'上個類和'@ NotNull'或'@ NotEmpty'在球場上和驗證工作,你必須有一個您的類路徑上的JSR-303驗證程序,例如「hibernate-validation」。只添加註釋'@ Validation'不會產生任何結果。 –

回答

1

我在10分鐘前就有同樣的問題! 試着在你的配置中添加這個bean:

@Bean 
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 
     PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer(); 
     propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true); 
     return propertySourcesPlaceholderConfigurer; 
    } 
+0

好找,但實際上這是解決相反問題的方法。我不想隱瞞錯誤,我想保留它。 –

+0

你必須手動使你的屬性類實現'InitializingBean'並重寫'afterPropertiesSet()'方法,你可以通過反射每個字段的值來檢查並拋出異常,以防它們爲null。 – DeejonZ

+0

這聽起來不太優雅,除了屬性不會最終爲空,它們最終還是嵌入在字符串中的佔位符值。 –