Home > Mobile >  How do I make a Map<String, List<String>> with SpEL?
How do I make a Map<String, List<String>> with SpEL?

Time:11-30

I'm making a config in my Spring application and I want to define a map:

@Value("${ordering:#{{:}}")
private Map<String, List<String>> ordering;

Here's what's in my config:

ordering = {'SOMEVALUE' : {'ONE', 'THREE', 'TWO'}, 'OTHERVALUE' : {'THREE', 'ONE', 'TWO'}}

But this always gets read as null (so I assume invalid SpEL).
The name of the variable and config value aren't misspelled and other values are loaded from the same config, so those parts are set up properly.
How should such a map be defined, what am I screwing up? Is there an online tool for parsing SpEL?

I tried several things: adding and removing the single ticks, same for double ticks and wrapping the lists in an extra {}, but none of these helped and the value is still set to null.
I also tried modifying the annotation, to no avail:

@Value("#{${ordering:#{{:}}}")

CodePudding user response:

Two changes are needed.

First change:

The entry in the config file needs to be adjusted. SpEL uses a {key:value} notation (reference), where the key should not be enclosed in quotes.

So, use this:

ordering = {SOMEVALUE : {'ONE', 'THREE', 'TWO'}, OTHERVALUE : {'THREE', 'ONE', 'TWO'}}

Second change:

Now you can refer to this as follows in your Java:

@Value("#{${ordering}}")
private Map<String, List<String>> ordering;

And if you want to provide a default empty map, you can use {:} as follows:

@Value("#{${ordering_MISSING : {:} }}")
private Map<String, List<String>> ordering2;

Because there is no property called ordering_MISSING, the default will be used.

Reference: inline maps

{:} by itself means an empty map.


"is there an online tool for parsing SpEL?" - I am not aware of one. Someone else may know of one.

CodePudding user response:

I think I figured out what I was doing wrong: My actual SpEL might have been correct at some point, but I'm parsing the data read from that and storing it in another variable, at which point ordering was null. What I forgot to consider is that the other field I'm parsing ordering into might (and does) get evaluated first.

  • Related