Cannot bind Map to Object in Spring Configuration Properties from YAML file

748 Views Asked by At

I have the following configuration in my Spring boot's application.yml file:

project:
 country-properties:
   france:
     capital: paris
     population: 60  

And I have the the properties class : CountryProperties :

@Getter
@AllArgsConstructor
@ConstructorBinding
@ConfigurationProperties(prefix="project.country-properties") 
public class CountryProperties {
      private Map<String, CountryData> countryProperties;

      @Getter
      @Setter
      public static class CountryData {
          private String capital; 
          private Integer population; 
      }   

However my CountryProperties is always null, and it's because of a failed mapping with the CountryData object. Any ideas what is wrong with what I wrote?

1

There are 1 best solutions below

3
Sy3d On

You have the annotation @ConstructorBinding. This annotation tells Spring to look for a constructor in your class that has parameters corresponding to your configuration properties, and then will bind the properties.

What you are missing is:

public CountryProperties(Map<String, CountryData> countryProperties) {
    this.countryProperties = countryProperties;
}

Update:

After inspecting your code again, it looks like you aren't mapping the configuration correctly to the instance field. Please update your @ConfigurationProperties(prefix="project.country-properties") to @ConfigurationProperties(prefix="project").

Also replace the @ConstructorBinding with @Configuration.