[英]spring boot expand configuration properties metadata json “hints” for Map not work
[英]Spring configuration properties metadata json for nested list of Objects
如何为嵌套的对象列表配置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
}
这是元数据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中配置子属性?
如下所示,编辑器无法识别子属性。
对于您的问题:“如何在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>"
IDE将获得列表能够接受的类。 IDE 应使用类名来推断NestedObject
上的可用属性。 但是,在撰写本文时,并非所有IDE都完全反映了属性和YAML格式的嵌套类。
IntelliJ似乎反映了属性文件中列表的值类型,但它没有反映到地图值类型中。 它根本不反映YAML文件的列表或映射值。 我不确定Spring Tool Suite,但上次检查时,它对自动完成的支持也缺少这些功能。
如果您是IntelliJ用户,我建议对这两个问题进行投票,以便支持对集合类型的完全支持:
即使IDE无法识别这些属性,您已经完成的工作也可以正常使用Spring Boot。 如果你想改进IDE如何使用Spring Boot配置yaml文件,那么Robert Thomton建议的是要走的路。
IntelliJ解决方法
IntelliJ中的这些黄色标记是源自检查的警告标记(首选项 - >编辑器 - >检查)。 在许多情况下,这些标记可以被忽略,因为在使用框架和语言的新功能时它们通常是误报。 因此,如果他们打扰你,你可以只为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元数据文档相对应。 您列出的元数据文件不包含NestedObject属性的条目。 如果您将鼠标悬停在黄线上并切换快速修复 ,IntelliJ将建议修复:
警告不会立即消失。 但是如果你做一个干净的构建 (取决于你的构建工具),它们就会消失。
如果您现在打开target / META-INF / spring-configuration-metadata.json,您可以看到Spring Boot已添加了之前“快速修复”生成的additional-spring-configuration-metadata.json的内容。
您可以修改此additional-spring-configuration-metadata.json文件以为IDE提供其他帮助,例如属性中的有效值。 希望随着时间的推移IntelliJ足够聪明,所以我们不需要手动编辑这个文件。
这样做是为了原始警告,但现在如果您查看application.yaml,您可以看到一些新的警告:
想法官方spring-boot插件到目前为止不支持通用的nest对象(2019.5)
解决方法:安装“Spring Assistant”插件(停止更新1年,但仍可与官方插件一起使用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.