Home > database >  What should the format of a map with list look like in SpEL
What should the format of a map with list look like in SpEL

Time:11-08

I'm trying to read a map of lists from application.properties in a spring batch application

ExpressionParser parser = new SpelExpressionParser();
Map<String, List<String>> mapOfLists = (Map<String, List<String>>) parser.parseExpression("{'KEY1':{'value1','value2'},'KEY2':{'value3','value4'},'KEY3': {'value5'}}").getValue();

The above works fine but when I put the same value in application.properties as map-of-lists={'KEY1':{'value1','value2'},'KEY2':{'value3','value4'},'KEY3': {'value5'}} and try to read the key using @Value("#{${map-of-lists}}") final Map<String, List<String>> mapOfLists spring isn't happy and errors out saying it cant find the value.

The same works if I update the key and @Value type to Map<String, String>

I did not read into how spring is parsing the value but is there a way to do this?

Also, is @Value a good way to read from application.properties for a map of lists?

CodePudding user response:

Try this:

@Value("#{${map-of-lists}}")
private Map<String, List<String>> mapOfLists;

application.properties

map-of-lists={'KEY1':{'value1','value2'}, 'KEY2':{'value1','value2'}}

In the case of application.yml it should be:

map-of-lists: "{'KEY1':{'value1','value2'}, 'KEY2':{'value1','value2'}}"

CodePudding user response:

After a lot of looking and debugging the below works. I had to add escape character for , and that did the job

map-of-lists={KEY1:{value1\,value2}\,KEY2:{value3\,value4}\,KEY3:{value5}}

this can later be read as

@Value("#{${map-of-lists}}") final Map<String, List<String>> mapOfLists
  • Related