Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help figured out how to load nested list from yml in spring boot java app

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!

like image 734
Brad Avatar asked Nov 13 '15 18:11

Brad


1 Answers

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.

like image 57
Yonatan Wilkof Avatar answered Nov 14 '22 22:11

Yonatan Wilkof