给定一些带有无法解析占位符的应用程序配置,如以下 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:无法解析值“${missing-placeholder}/whatever”中的占位符“missing-placeholder”
。这是因为该值是由 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; }
}
没有异常(exception)。我可以看到 PropertySourcesPropertyValues.getEnumerableProperty
捕获了带有注释 //可能无法解析占位符,在此处忽略它
的异常,并将无效值收集到其内部映射中。后续数据绑定(bind)不会检查未解析的占位符。
我检查过,简单地将 @Validated
和 @Valid
注释应用于类和字段并没有帮助。
是否有任何方法可以通过 ConfigurationProperties
绑定(bind)保留在未解析的占位符上引发异常的行为?
最佳答案
显然没有更好的解决方案。至少这比 afterPropertiesSet() 好一些。
@Data
@Validated // enables javax.validation JSR-303
@ConfigurationProperties("my.config")
public static class ConfigProperties {
// with @ConfigurationProperties (differently than @Value) there is no exception if a placeholder is NOT RESOLVED. So manual validation is required!
@Pattern(regexp = ".*\$\{.*", message = "unresolved placeholder")
private String uri;
// ...
}
更新:我第一次得到了正则表达式错误。它匹配整个输入(不仅仅是 java.util.regex.Matcher#find()
)。
关于spring - Spring Boot 配置属性 Unresolved 占位符验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43493346/