Agent Smith
Agent Smith

Reputation: 55

Get values into a map using spring el

I have a value in a properties file that goes

currency.codes=US:USD,IN:INR,AU:AUD

I am looking to get these values into a map with a (key,value) pair like (US,USD) etc using spring el I'm trying something like

@Value("#{'${currency.codes}'.split(',|:')}")
    private Map<String, String> myMap;

This obviously doesn't work. But I would be grateful if anyone can suggest me with such minimal code or any other alternate solution. There are a lot of properties like this that I need to get into maps. -TIA

Upvotes: 1

Views: 1262

Answers (1)

Raniz
Raniz

Reputation: 11113

You can write a static helper method and use that in your expression to reduce the complexity of the SpEL code.

public class MapDecoder {
    public static Map<String, String> decodeMap(String value) {
        Map<String, String> map = new LinkedHashMap<>();
        String[] pairs = value.split(",");
        for (String pair : pairs) {
            String[] parts = pair.split(":");
            map.put(parts[0], parts[1]);
        }
        return map;
    }
}

public class MyBean {
    @Value("#{T(mypackage.MapDecoder).decodeMap('${currency.codes}')}")
    private Map<String, String> myMap;
}

Upvotes: 1

Related Questions