salvador
salvador

Reputation: 1089

Bind YAML properties to Map<String, List<String>> type with Spring Boot

I know that if I put the properties in the .yml file like that:

list
  - item 1
  - item 2

I can bind them to a java.util.List or Set type. Also If yaml properties are like that:

map:
  key1: value1
  key2: value2

I can bind thet to a Map. I wonder though if it is possible to bind yml properties to a Map<String, List<String>> type..

Upvotes: 8

Views: 21081

Answers (2)

Chandrakant Audhutwar
Chandrakant Audhutwar

Reputation: 345

thanks it helped me :) more descriptive answer I'm posting here.

Config class -

@ConfigurationProperties(prefix = "configuration.mymapwithlist")
public class ConfigUtilClass implements IConfigUtilClass {
    private Map<String, List<String>> myMap = new HashMap<>();

    @Override
    public Map<String, List<String>> getMyMap() {
        return myMap;
    }

}

yaml -

configuration: 
    mymapwithlist:
        myMap:
            key1:
                - value 1
                - value 2
                - value 3
                - value 4
            key2:
                - value 1
                - value 2
                - value 3
                - value 4
            '[key 3]':
                - value 1
                - value 2
                - value 3
                - value 4
            '[key 4]':
                - value 1
                - value 2
                - value 3
                - value 4

if your keys having spaces then, put keys in [ key 4 ].

Upvotes: 0

abosancic
abosancic

Reputation: 1815

try to add this:

private Map<String, List<String>> keysList;

and put this in your .yml file

keysList:
    key1: 
        - value1
        - value2  
    key2: 
        - value2
        - value3
    key3: 
        - value3
        - value4

The result should be List mapping:

keysList={key1=[value1, value2], key2=[value2, value3], key3=[value3, value4]}

If you use on this way

private Map keysList;

you will get Map mapping.

keysList={key1={0=value1, 1=value2}, key2={0=value2, 1=value3}, key3={0=value3, 1=value4}}

Upvotes: 7

Related Questions