Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 308
salvador Avatar asked May 28 '15 14:05

salvador


People also ask

How to inject map from a YAML file in Spring Boot?

3. How to Inject a Map from a YAML File Spring Boot has taken data externalization to the next level by providing a handy annotation called @ConfigurationProperties. This annotation is introduced to easily inject external properties from configuration files directly into Java objects.

How to bind a YAML list to a list<object> in Spring Boot?

Binding a YAML List to a Simple List of Objects Spring Boot provides the @ConfigurationProperties annotation to simplify the logic of mapping external configuration data into an object model. In this section, we'll be using @ConfigurationProperties to bind a YAML list into a List<Object>. We start by defining a simple list in application.yml:

What is the difference between Spring Boot properties files and YAML?

As a matter of fact, the hierarchical nature of YAML significantly enhances readability compared to properties files. Another interesting feature of YAML is the possibility to define different properties for different Spring profiles. Starting with Boot version 2.4.0, this is also possible for properties files.

How to map a list to a MultiValueMap in Spring Boot?

Spring Boot @ConfigurationProperties supports using a MultiValueMap to map the list into a Map<String, List<String>> object. In order to read the spring.profiles.active, we can change our Map to a MultiValue Map. Using that, we can verify list of all the active profiles is loaded correctly.


1 Answers

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

like image 81
abosancic Avatar answered Sep 21 '22 16:09

abosancic