Search code examples
javaspringspring-boot-configuration

Loading HashMap to a nested configuration bean throws Binding Exception


I was attempting this example given here : https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties

All worked well except when attempted added another properties to load hashmap values

property added as:

    demoapp.security.policies={'KEY1': 'value1', 'KEY2': 'value3', 'KEY3': 'value5'}

And inside Secutiry inner class, added another variable as below:

private Map<String, String> policies;

public Map<String, String> getPolicies() {
  return policies;
}

public void setPolicies(Map<String, String> policies) {
  this.policies = policies;
}

But this throws error as :

    Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.util.Map<java.lang.String, java.lang.String>]

Interestingly if I put this in a normal(non-nested) configuration class it works fine for me.

What is going wrong here, any suggestions please


Solution

  • When binding to a map, you're binding nested properties, so you need to specify the properties separately.

    Properties file:

    demoapp.security.policies.KEY1=value1
    demoapp.security.policies.KEY2=value3
    demoapp.security.policies.KEY3=value5
    

    YAML file:

    demoapp.security.policies:
      "[KEY1]": value1
      "[KEY2]": value3
      "[KEY3]": value5