I am using snakeYaml to parse certain configuration/property values to a Configuration object.
My yaml file looks like this -
#Thread batchLimit: 1000 threadCountLimit: 2 #Some More Config key: value #MAP keyMapping: <What goes here?>
My Configuration class looks like this -
public class Configuration{ int batchlimit; int threadCountLimit; ... Map<String,String> keyMapping; }
How do I define the keyMapping
in the YAML file so it reads directly through SnakeYAML?
We create our POJO configuration class: @ConfigurationProperties(prefix = "t-shirt-size") public class TshirtSizeConfig { private Map<String, Integer> simpleMapping; public TshirtSizeConfig(Map<String, Integer> simpleMapping) { this. simpleMapping = simpleMapping; } //getters and setters.. }
In YAML, maps are represented using the colon ( : ) character. We can also use quotation marks ( " or ' ) to enclose the keys and values if we need to.
In order to create Map instances from YAML or properties file configurations, we need a @ConfigurationProperties class. This class is required for containing all the nested Map groups. As we want to read all the properties under the group “spring”, our properties class uses it as a prefix.
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.
Here is how it can look like:
#MAP keyMapping: key1: value1 key2: value2
Generally YAML format has natural support of key-value pairs. Take a look on the following tutorial (just for example): https://github.com/Animosity/CraftIRC/wiki/Complete-idiot's-introduction-to-yaml
Or just google "yaml map" for more details.
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