Search code examples
spring-bootpropertiesconfigurationhashmapconfiguration-files

How can I load propeties in a Map with SpringBoot?


I try to initialize a Map in my SpringBoot application but I am doing something wrong.

My config.properties:

myFieldMap.10000.fieldName=MyFieldName
myFieldMap.10000.fieldName2=MyFieldName2
myFieldMap.10001.fieldName=MyFieldName
myFieldMap.10001.fieldName2=MyFieldName2
myFieldMap.10002.fieldName=MyFieldName
myFieldMap.10003.fieldName2=MyFieldName2
...

(Isn't it possible to use some kind of bracket notation like myFieldMap[10001].fieldName for maps (I saw it used for lists). I tried with my MyConfig.class:

@PropertySource("classpath:config.properties")      
@Component
public class MyConfig {
    private java.util.Map<Integer, MyMapping> theMappingsMap = new HashMap<Integer, MyMapping>();

    public Map<String, MyMapping> getTheMappingsMap() {
        return theMappingsMap;
    }
    public void setTheMappingsMap(Map<String, MyMapping> theMappingsMap) {
        this.theMappingsMap= theMappingsMap;
    }

    public class MyMapping {
        private String fieldName;
        private String fieldName2;

        public String getFieldName() {
            return fieldName;
        }

        public String getFieldName2() {
            return fieldName2;
        }

        public void setFieldName(final String fieldName) {
            this.fieldName = fieldName;
        }

        public void setFieldName2(final String fieldName) {
            this.fieldName2 = fieldName;
        }
    }
}

How do I have to adapt my code to let SpringBoot initialize my configuration (Map) with the definitions in the config.properties file?


Solution

  • You are missing @ConfigurationProperties annotation. Try this

    @PropertySource("classpath:config.properties")
    @Configuration
    @ConfigurationProperties
    public class MyConfig {
      private java.util.Map<String, MyMapping> myFieldMap = new HashMap<>();
      ....
    }
    

    Another issue with your code is, if you want to make MyMapping class as an inner class of MyConfig, then you need to declare it as static. Or else you can make it as a separate class.