java 如何指定嵌套属性的默认值?

ecfsfe2w  于 2023-06-04  发布在  Java
关注(0)|答案(2)|浏览(198)

下面的代码在我没有为acme.security.roles指定值时抛出NPE:

@ConstructorBinding
@ConfigurationProperties("acme")
public class AcmeProperties {

    private final Security security;

    public AcmeProperties(Security security) {
        this.security = security;
    }

    public Security getSecurity() {
        return security;
    }

    public static class Security {

        private final List<String> roles;

        public Security(@DefaultValue("USER") List<String> roles) {
            this.roles = roles;
        }

        public List<String> getRoles() {
            return roles;
        }
    }
}
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(AcmeProperties.class)
public class MyConfiguration {

@Bean HttpClientConnectionManager httpClientConnectionManager(AcmeProperties acmeProperties) {

        Security security = acmeProperties.getSecurity();

        security.getRoles(); // throws NPE

        return new PoolingHttpClientConnectionManager();
    }
}

让spring Boot 示例化Security对象并使用默认值roles的正确方法是什么?我应该使用@DefaultValue和SPEL来使它工作吗?

83qze16e

83qze16e1#

试试这个应该能行

@Configuration
@ConfigurationProperties(prefix = "acme")
public class AcmeProperties {

    private Security security;

    public Security getSecurity() {
        return security;
    }

    public void setSecurity(Security security) {
        this.security = security;
    }

    @PostConstruct
    public void initDefaultValues() {
        if(security == null) {
            security = new Security();
        }
    }
}

安全类将如下所示

public class Security {

    private List<String> roles = Lists.newArrayList("USER");

    public List<String> getRoles() {
        return roles;
    }

    public void setRoles(List<String> roles) {
        this.roles = roles;
    }
}
1sbrub3j

1sbrub3j2#

从Sping Boot 2.2.7开始,可以将@DefaultValue(无参数)添加到security构造函数参数:

public AcmeProperties(@DefaultValue Security security) {
    this.security = security;
}

相关问题