Configuration properties for Java – map
I have the following structure in my Spring Boot yaml file:
countryConfiguration:
NL:
address:
postcodeKeyboardType: ALPHANUMERIC
postcodeExample: 1111 AA
cityExample: Amsterdam
ES:
address:
postcodeKeyboardType: NUMERIC
postcodeExample: 11111
cityExample: Madrid
I want to create a configuration property class to access these values. I have something like this :
@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;
}
}
}
But it doesn’t work, I see:
bind to target org.springframework.boot.context.properties.bind.BindException: Cannot bind property under “” to io.bux.onboarding.application.config.CountryConfigurationProperties$$ EnhancerBySpringCGLIB$$1d9a5856 Failed:
Property: .countryConfiguration
Value: null
Reason: must not be null
If I remove the static inner class Configuration and then put in Object, it works….
Solution
I noticed that the address field is of type Object
. I want it to be of type Address and have an inner class that represents the Address
object.
In the code snippet below, I added an Address class to match the yml configuration you are using. I’ve tested this and it starts successfully and maps the properties accordingly.
@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;
}
}
}