Parse Properties To Maps With Spring El

Spring EL allows to map strings into complex objects. We can leverage that to store and read non trivial configuration from properties files.

You can use the SPEL json-like syntax to write a simple map or a map of list in property file.{'KEY1': 'value1', 'KEY2': 'value3', 'KEY3': 'value5'}
      'KEY1': {'value1','value2'}, \
      'KEY2': {'value3','value4'}, \
      'KEY3': {'value5'} \

I used \ for multiline property to enhance readability

Then, in Java, you can access and parse it automatically with @Value like this.

    Map<String, String> simpleMap;
    Map<String, List<String>> mapOfList;

Here with ${}, @Value gets the following String from the property file:

    "{'KEY1': 'value1', 'KEY2': 'value3', 'KEY3': 'value5'}"

Then, it is evaluated as if it was inlined

    @Value("#{ { 'KEY1': 'value1', 'KEY2': 'value3', 'KEY3': 'value5'} }")

You can learn more in the official documentation

Written on September 25, 2018
Licence Creative Commons
Ce(tte) œuvre est mise à disposition selon les termes de la Licence Creative Commons Attribution 4.0 International.