下面的代码在我没有为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来使它工作吗?
2条答案
按热度按时间83qze16e1#
试试这个应该能行
安全类将如下所示
1sbrub3j2#
从Sping Boot 2.2.7开始,可以将
@DefaultValue
(无参数)添加到security
构造函数参数: