首页 > 解决方案 > 在 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 = truein @ConfigurationProperties,但这不完全是我想要的行为,因为在我的情况下空值是有效的。

有没有办法可以忽略未绑定的属性?我能做些什么来避免这个问题?

更新

进一步调试后,我可以看到,因为此时返回ignoreUnkownFields = false@ConfigurationPropertesa 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;
    }
}

有什么办法可以避免这种情况吗?

标签: javaspringspring-boot

解决方案


推荐阅读