Spring:@ConfigurationProperties中的@NestedConfigurationProperty列表

clo*_*aut 4 configuration spring properties spring-boot

嗨,我正在尝试启动并运行以下配置.

@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;
}
Run Code Online (Sandbox Code Playgroud)

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

my.servers[0].name=test
my.servers[0].server.name=test
my.servers[1].name=test
my.servers[1].server.name=test
Run Code Online (Sandbox Code Playgroud)

Mac*_*iak 6

  • 您需要添加 setter 和 getterServerConfiguration
  • 您不需要使用嵌套属性来注释类@ConfigurationProperties
  • ServerConfiguration.description名称和属性之间不匹配my.servers[X].server.name=test


Ste*_*oll 6

扩展Maciej已经说过的话.

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

@NestedConfigurationProperty使用由元数据生成器(以指示属性是不是一个单一的值,但是我们应该探讨,以产生附加的元数据.在的情况下List没有特性的任何有限量,以便所述元数据必须在列表中停止.

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