鉴于有无法解决的占位符某些应用程序配置,如下所示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'不会产生任何结果。 –