我的春季启动yaml文件中具有以下结构:
countryConfiguration:
NL:
address:
postcodeKeyboardType: ALPHANUMERIC
postcodeExample: 1111 AA
cityExample: Amsterdam
ES:
address:
postcodeKeyboardType: NUMERIC
postcodeExample: 11111
cityExample: Madrid
我想创建一个配置属性类来访问这些值。我有这样的东西:
@Configuration
@ConfigurationProperties
@Validated
public class CountryConfigurationProperties {
@NotNull
private Map<String, Configuration> countryConfiguration;
public Map<String, Configuration> getCountryConfiguration() {
return countryConfiguration;
}
public void setCountryConfiguration(Map<String, Configuration>
countryConfiguration) {
this.countryConfiguration = countryConfiguration;
}
public static class Configuration {
private Object address;
public Object getAddress() {
return address;
}
public void setAddress(Object address) {
this.address = address;
}
}
}
但是它不起作用,我得到了: 绑定到目标org.springframework.boot.context.properties.bind.BindException:无法将“”下的属性绑定到io.bux.onboarding.application.config.CountryConfigurationProperties $$ EnhancerBySpringCGLIB $$ 1d9a5856失败:
Property: .countryConfiguration
Value: null
Reason: must not be null
如果我删除静态内部类Configuration,然后放入Object,它就可以工作...
答案 0 :(得分:2)
我注意到地址字段的类型为Object
。我希望它的类型为Address
,并且有一个表示Address对象的内部类。
在下面的代码片段中,我添加了一个Address类以匹配您使用的yml配置。我已经对此进行了测试,它可以成功启动并相应地映射属性。
@Validated
@Component
@ConfigurationProperties
public class CountryConfigurationProperties {
@NotNull
private Map<String, Configuration> countryConfiguration;
public Map<String, Configuration> getCountryConfiguration() {
return countryConfiguration;
}
public void setCountryConfiguration(Map<String, Configuration> countryConfiguration) {
this.countryConfiguration = countryConfiguration;
}
public static class Configuration {
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
public static class Address {
private String postcodeKeyboardType;
private String postcodeExample;
private String cityExample;
public String getPostcodeKeyboardType() {
return postcodeKeyboardType;
}
public void setPostcodeKeyboardType(String postcodeKeyboardType) {
this.postcodeKeyboardType = postcodeKeyboardType;
}
public String getPostcodeExample() {
return postcodeExample;
}
public void setPostcodeExample(String postcodeExample) {
this.postcodeExample = postcodeExample;
}
public String getCityExample() {
return cityExample;
}
public void setCityExample(String cityExample) {
this.cityExample = cityExample;
}
}
}