In this short tutorial, we’re going to have a closer look at how to map a YAML list into a List in Spring Boot.
We’ll start with some background on how to define lists in YAML.
Then we’ll dig deeper to see how to bind YAML lists to Lists of objects.
2. Quick Recap About Lists in YAML
In short, YAML is a human-readable data serialization standard that provides a concise and clear way to write configuration files. *The good thing about YAML is the fact that it supports multiple data types such as Lists, Maps and scalar types.*
The elements in a YAML list are defined using the “-” character, and they all share the same indentation level:
yamlconfig:
list:
- item1
- item2
- item3
- item4
As a comparison, the properties-based equivalent uses indices:
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.
It’s worth mentioning that Spring Boot provides out-of-the-box support for YAML configuration. By design, Spring Boot loads configuration properties from application.yml at startup without any extra work.
3. 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