I have a yaml file setup like this:
system:
locators:
- first.com
- 103
- 105
- second.com
- 105
I want to load this as @autowired
configuration that looks something like this:
@Autowired
List<Locator> locators;
I'm thinking that the Locator class would look something like this:
class Locator {
String name;
List<String> ports;
}
But I'm not sure how to put this all together. Any help is appreciated!
Firstly, I believe your yaml file structure is invalid. In your Locator class you have given names to the fields - you should do the same in your yaml file. In the end it should look like this:
system:
locators:
- name: first.com
ports:
- 103
- 105
- name: second.com
ports:
- 105
Secondly, you can leverage Spring Boot's rather advanced properties-to-bean auto mapping. As in every Spring Boot app, you need to annotate your main class with @SpringBootApplication. Then, you can create a class representing your properties structure:
@Configuration
@ConfigurationProperties(prefix = "system")
public class SystemProperties {
private List<Locator> locators;
public List<Locator> getLocators() {
return locators;
}
public void setLocators(List<Locator> locators) {
this.locators = locators;
}
public static class Locator {
private String name;
private List<String> ports;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPorts() {
return ports;
}
public void setPorts(List<String> ports) {
this.ports = ports;
}
}
}
Notice the @ConfigurationProperties annotation that defines the prefix which is the root of this classe's mapped configuration. It can of course be any node in a yaml tree of properties, not necessarily the main level as in your case.
For further reading I would suggest this blog post and the official documentation as there are more ppowerful abilities when it comes to property bean mapping.
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