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

与世无争的帅哥 提交于 2020-07-08 09:38:52

问题


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..


回答1:


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}}




回答2:


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 ].



来源:https://stackoverflow.com/questions/30510151/bind-yaml-properties-to-mapstring-liststring-type-with-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!