How to construct map with values in application.yml file, I was able to create a list of Objects but I'm looking for how can I construct Map
Here is my application.ymal file
parentkey:
child:
- key1: 123
key2:
subkey: value1
key3:
subkey1: value2
subkey3: value3
key4:
subkey4: value4
- key1: 123
key2:
subkey: value5
key3:
subkey1: value6
subkey3: value7
key4:
subkey4: value8
and I created my like this:
@Configuration
@ConfigurationProperties("parentkey")
public class ConfigurationTest {
private List<Configuration> child;
}
now in my ConfigurationTest class can I get Map with key as value of key1 and value as Object contains key2 to ke4
if yes, how Can I construct my application.ymal file
CodePudding user response:
The map in yml can be created like this
parentkey:
child:
123:
key2:
subkey: value1
key3:
subkey1: value2
subkey3: value3
key4:
subkey4: value4
234:
key2:
subkey: value5
key3:
subkey1: value6
subkey3: value7
key4:
subkey4: value8
This can be read the same way Map<String, Object> child where keys will be 123 and 234.
CodePudding user response:
Spring can translate YAML into a variety of object types, including user-defined classes as well as things like List<>
and Map<>
. It is also recursive; it can translate nested objects into other types.
Knowing that, you can define an @ConfigurationProperties
class that contains a Map<>
and Spring will automatically create the objects to populate your map as long as it can figure out how to translate the key and value types.
For example, using a properties class like this:
@Component
@ConfigurationProperties(prefix = "parentkey")
public class MyConfigProps {
private Map<String, String> children;
// getters and setters
}
This YAML will populate an instance of that class:
parentkey:
children:
- key1: 123
- key2: abc
In the question it looks like the children nodes are not all of the same type; some are simple integer or string values, some have nested children themselves. So you'll have to tweak my example to match the actual structure you need to support. But since Spring can translate arbitrarily nested structures/objects, almost anything is possible.