鑑於有無法解決的佔位符某些應用程序配置,如下所示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
綁定的行爲?
你應該,但'@ Validated'上個類和'@ NotNull'或'@ NotEmpty'在球場上和驗證工作,你必須有一個您的類路徑上的JSR-303驗證程序,例如「hibernate-validation」。只添加註釋'@ Validation'不會產生任何結果。 –