【问题标题】:Spring: @NestedConfigurationProperty List in @ConfigurationPropertiesSpring:@ConfigurationProperties 中的@NestedConfigurationProperty 列表
【发布时间】:2015-09-08 05:40:15
【问题描述】:

您好,我正在尝试启动并运行以下配置。

@ConfigurationProperties(prefix="my")
public class Config {

    @NestedConfigurationProperty
    private List<ServerConfiguration> servers = new ArrayList<ServerConfiguration>();

    public List<ServerConfiguration> getServers() {
        return this.servers;
    }
}

@ConfigurationProperties(prefix = "server")
public class ServerConfiguration {
    private String name;
    private String description;
}

所以,我想在对象中嵌套多个服务器配置。 我尝试使用以下属性文件设置属性。我可以看到列表是按项目添加的,但服务器的成员从未设置(名称、描述)

my.servers[0].name=test
my.servers[0].server.name=test
my.servers[1].name=test
my.servers[1].server.name=test

【问题讨论】:

    标签: spring properties configuration spring-boot


    【解决方案1】:

    扩展 Maciej 已经说过的话。

    @ConfigurationProperties 应该只在 root 对象上设置(即负责处理给定前缀的对象。不需要用它注释嵌套对象。

    @NestedConfigurationProperty由元数据生成器使用(表示属性不是单个值,而是我们应该探索以生成其他元数据的东西。在List 没有任何有限数量的属性,因此元数据将不得不停在列表中。

    在任何情况下,每个奇异属性都需要一个 getter 和一个 setter。我们不进行字段绑定,我们需要一个公共 getter 以避免在元数据中暴露不必要的属性。

    【讨论】:

    • 感谢您提到 getter 的需要,我花了一段时间才找到为什么我的嵌套属性没有被填充。原来是因为缺少吸气剂。
    【解决方案2】:
    • 你需要添加setter和getter到ServerConfiguration
    • 您不需要使用@ConfigurationProperties 注释具有嵌套属性的类
    • ServerConfiguration.description 和属性 my.servers[X].server.name=test 之间的名称不匹配

    【讨论】:

      猜你喜欢
      • 2018-06-27
      • 2018-12-25
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      相关资源
      最近更新 更多