java - 在 Spring Boot 2 中忽略 ConfigurationProperties 的未绑定属性
问题描述
我在 application.yml 文件中遇到了未绑定属性的问题。我正在从 Spring Boot 1.5.4 迁移到 Spring Boot 2。我的问题是我有一些属性可以选择留空,例如:
应用程序.yml
app:
enabled: false
url: #ldap://127.0.0.1:3268
user: #admin
在这种情况下,如果ldap.enabled
设置为true
,则ldap
可以将属性设置为当前注释掉的所需值。但是,如果ldap.enabled
设置为,false
则其余属性未设置并留空。
在我的 Spring Boot 1.5.4 应用程序中,我对此没有任何问题,但现在升级到 Spring Boot 2 后,我得到以下异常:
org.springframework.boot.context.properties.bind.UnboundConfigurationPropertiesException: The elements [ldap.ignorecertificate] were left unbound.
org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'ldap' to com.myapp.server.config.properties.LdapProperties
LdapProperties.java
@Component
@ConfigurationProperties(prefix = "app", ignoreUnknownFields = false)
@Getter
@Setter
public class AppProperties {
private Boolean enabled;
private String url;
private String user;
}
我知道我可以设置ignoreUnvalidFields = true
in @ConfigurationProperties
,但这不完全是我想要的行为,因为在我的情况下空值是有效的。
有没有办法可以忽略未绑定的属性?我能做些什么来避免这个问题?
更新
进一步调试后,我可以看到,因为此时返回ignoreUnkownFields = false
了@ConfigurationPropertes
a NoUnboundElementsBindHandler
,它检查未绑定的属性:
class ConfigurationPropertiesBinder {
private final ApplicationContext applicationContext;
private final PropertySources propertySources;
private final Validator configurationPropertiesValidator;
private final boolean jsr303Present;
private volatile Validator jsr303Validator;
private volatile Binder binder;
...
...
...
private BindHandler getBindHandler(ConfigurationProperties annotation,
List<Validator> validators) {
BindHandler handler = new IgnoreTopLevelConverterNotFoundBindHandler();
if (annotation.ignoreInvalidFields()) {
handler = new IgnoreErrorsBindHandler(handler);
}
if (!annotation.ignoreUnknownFields()) {
UnboundElementsSourceFilter filter = new UnboundElementsSourceFilter();
handler = new NoUnboundElementsBindHandler(handler, filter);
}
if (!validators.isEmpty()) {
handler = new ValidationBindHandler(handler,
validators.toArray(new Validator[0]));
}
return handler;
}
}
有什么办法可以避免这种情况吗?
解决方案
推荐阅读
- python - 基于列表长度设置限制的 Pythonic 方式
- gam - 如何使用 Google Ad Manager 将预投标视频广告添加到我的网站
- python - 为什么 python unittest assertRaises 方法不注册抛出的异常?
- reactjs - React Redux Saga 与 Typescript 错误属性不存在
- excel - 组合框列位置
- if-statement - ifelse 在我想要 0 时给我 NA
- flutter - 如何仅隐藏 TextField 中的某些文本
- gradle - 任务计数与 gradle build 命令输出中显示的可操作任务之间有什么关系?
- amazon-web-services - 如何使用 Power Shell 为 AWS IAM 策略设置标签
- firebase - Firebase 电话验证 OTP 某些号码已验证,其他号码在 PHONE 中收到 OTP 后未验证,当我将颤振应用程序上传到 Play 商店时,