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..
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.
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:
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.
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.
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With