嵌套的对象列表的Spring配置属性元数据json

Ola*_*nka 6 java spring json spring-mvc

如何为嵌套的对象列表配置spring配置元数据json?

脚本

@ConfigurationProperties(prefix = "custom-config")
public class ConfigProperties {

    private boolean booleanProperty;
    private List<NestedObject> listProperty = new LinkedList<>();

    //getters and setters
}

public class NestedObject {

    private String stringProperty;
    private boolean booleanProperty;

    //getters and setters

}
Run Code Online (Sandbox Code Playgroud)

这是元数据json中自动生成的内容

{
  "groups": [{
    "name": "custom-config",
    "type": "testing.config.properties.ConfigProperties",
    "sourceType": "testing.config.properties.ConfigProperties"
  }],
  "properties": [
    {
      "name": "custom-config.boolean-property",
      "type": "java.lang.Boolean",
      "sourceType": "testing.config.properties.ConfigProperties",
      "defaultValue": false
    },
    {
      "name": "custom-config.list-property",
      "type": "java.util.List<testing.config.properties.NestedObject>",
      "sourceType": "testing.config.properties.ConfigProperties"
    }
  ],
  "hints": []
}
Run Code Online (Sandbox Code Playgroud)

如何在java代码或json中配置子属性?

如下所示,编辑器无法识别子属性.

在此输入图像描述

小智 8

对于您的问题:"如何在java代码或json中配置子属性?"

答案很长:

请参阅https://github.com/spring-projects/spring-boot/wiki/IDE-binding-features#simple-pojo

特别是,请查看"简单Pojo"和"Wrapping Up"部分.

简答:

你已尽力而为.IDE具有所需的所有信息.NestedObject可以根据输出第16行给出的信息通过反射确定属性:

"type": "java.util.List<testing.config.properties.NestedObject>"
Run Code Online (Sandbox Code Playgroud)

IDE将获得列表能够接受的类.IDE 使用类名来推断可用属性NestedObject.但是,在撰写本文时,并非所有IDE都完全反映了属性和YAML格式的嵌套类.

IntelliJ似乎反映了属性文件中列表的值类型,但它没有反映到地图值类型中.它根本不反映YAML文件的列表或映射值.我不确定Spring Tool Suite,但上次检查时,它对自动完成的支持也缺少这些功能.

如果您是IntelliJ用户,我建议对这两个问题进行投票,以便支持对集合类型的完全支持: