需要帮助找出如何在spring boot java app中从yml加载嵌套列表

Bra*_*rad 5 java yaml spring-boot

我有一个像这样的yaml文件设置:

system:
  locators:
  - first.com
    - 103
    - 105
  - second.com
    - 105
Run Code Online (Sandbox Code Playgroud)

我想加载这个@autowired配置看起来像这样:

@Autowired
List<Locator> locators;
Run Code Online (Sandbox Code Playgroud)

我认为Locator类看起来像这样:

class Locator {
    String name;
    List<String> ports;
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何把这一切都放在一起.任何帮助表示赞赏!

Yon*_*kof 7

首先,我相信您的yaml文件结构无效.在Locator类中,您已经为字段指定了名称 - 您应该在yaml文件中执行相同的操作.最后它应该是这样的:

system:
  locators:
  - name: first.com
    ports:
      - 103
      - 105
  - name: second.com
    ports:
      - 105
Run Code Online (Sandbox Code Playgroud)

其次,您可以利用Spring Boot的相当高级的属性到bean自动映射.与每个Spring Boot应用程序一样,您需要使用@SpringBootApplication注释主类.然后,您可以创建一个表示属性结构的类:

@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;
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

请注意@ConfigurationProperties注释,它定义了前缀,该前缀是此classe映射配置的根.它当然可以是yaml属性树中的任何节点,不一定是你的情况下的主要级别.

为了进一步阅读,我会建议这篇博客文章官方文档,因为在涉及属性bean映射时有更多有用的能力.