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

时间:2017-01-01 18:32:44

标签: java json spring spring-mvc

如何为嵌套的对象列表配置弹簧配置元数据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

}

这是元数据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": []
}

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

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

enter image description here

3 个答案:

答案 0 :(得分:8)

问题:&#34;如何在java代码或json中配置子属性?&#34;

长答案:

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

特别是,看看&#34; Simple Pojo&#34;和&#34;结束&#34;。

简答:

您已尽力而为。 IDE具有所需的所有信息。 NestedObject的属性可以通过基于输出第16行给出的信息的反射来确定:

"type": "java.util.List<testing.config.properties.NestedObject>"

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

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

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

答案 1 :(得分:0)

即使IDE无法识别这些属性,您已经完成的工作也可以正常使用Spring Boot。如果你想改进IDE如何使用Spring Boot配置yaml文件,那么Robert Thomton建议的是要走的路。

IntelliJ解决方法

IntelliJ中的这些黄色标记是源自检查的警告标记(首选项 - &gt;编辑器 - &gt;检查)。在许多情况下,这些标记可以被忽略,因为在使用框架和语言的新功能时它们通常是误报。因此,如果他们打扰你,你可以只为Spring Yaml文件禁用它们。

进一步调查

为此,您需要将 spring-boot-configuration-processor 作为依赖项

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

IntelliJ似乎使用spring-configuration-metadata.json来识别Spring Boot Configuration yaml文件中使用的映射。这与Spring Boot Configuration meta-data文档相对应。您列出的元数据文件不包含NestedObject属性的条目。如果您将鼠标悬停在黄线上并切换快速修复,IntelliJ将建议修复:

quick fix

IntelliJ将为您创建此文件: additional-spring-configuration-metadata.json

警告不会立即消失。但是如果你做了一个 clean build (取决于你的构建工具),它们就会消失。

如果您现在打开target / META-INF / spring-configuration-metadata.json ,您可以看到Spring Boot已添加了 additional-spring-configuration-metadata的内容。 json 以前的快速修复&#39;产生。

您可以修改此 additional-spring-configuration-metadata.json 文件,以便为IDE提供其他帮助,例如属性中的有效值。希望随着时间的推移IntelliJ足够聪明,所以我们不需要手动编辑这个文件。

这是针对原始警告的,但现在如果您查看application.yaml,您可以看到一些新的警告:

Duplicate configuration key

答案 2 :(得分:0)

idea官方spring-boot插件到目前为止不支持通用嵌套对象(2019.5)

解决方法:安装“ Spring Assistant”插件(已停止更新1年,但仍可与官方插件一起正常使用)

相关问题