Spring Boot 元数据文件的应用与生成
应用场景
Spring Boot jar包含元数据文件,提供所有支持的配置属性的详细信息。这些文件旨在允许IDE开发人员在用户使用application.properties 或application.yml文件时提供上下文帮助和“代码完成” 。
生成过程
- 添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true </optional>
</dependency>
- 项目打包
打包时,配置处理器会获取所有使用@ConfigurationProperties注解标注的类和方法来自动生成配置元数据,使用类属性的Javadoc填充配置元数据的description属性。
注意,配置处理器无法自动获取Enum和Collection数据类型的默认值,如果有默认值得情况下,最好手动提供其默认值。
生产元数据文件的目录为
/resources/META-INF/spring-configuration-metadata.json
手动添加
-
添加文件
补充元数据信息,可以手动在额外的json文件中配置元数据
/resources/META-INF/additional-spring-configuration-metadata.json -
自动合并
注解处理器会自动将 /resources/META-INF/additional-spring-configuration-metadata.json 中的项目合并到主元数据文件 spring-configuration-metadata.json 中。 -
文件属性
Group属性:较高级别的配置项,它对一类配置项进行分组,便于维护和管理。
Property属性:描述各属性名字、类型、默认值等信息。
hints属性:定义配置项的帮助信息,当用户使用该属性时提示用户可用的值有哪些,以及该值的作用描述等信息。
详细请参考 官方文档
- 示例
{"groups": [
{
"name": "server",
"type": "org.springframework.boot.autoconfigure.web.ServerProperties",
"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
},
{
"name": "spring.jpa.hibernate",
"type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate",
"sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties",
"sourceMethod": "getHibernate()"
}
...
],"properties": [
{
"name": "server.port",
"type": "java.lang.Integer",
"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
},
{
"name": "server.address",
"type": "java.net.InetAddress",
"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
},
{
"name": "spring.jpa.hibernate.ddl-auto",
"type": "java.lang.String",
"description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.",
"sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate"
}
...
],"hints": [
{
"name": "spring.jpa.hibernate.ddl-auto",
"values": [
{
"value": "none",
"description": "Disable DDL handling."
},
{
"value": "validate",
"description": "Validate the schema, make no changes to the database."
},
{
"value": "update",
"description": "Update the schema if necessary."
},
{
"value": "create",
"description": "Create the schema and destroy previous data."
},
{
"value": "create-drop",
"description": "Create and then destroy the schema at the end of the session."
}
]
}
]}
IDEA 添加
在 IDEA 中自定义配置会报warning, 无法理解配置属性, 其实也就是没从依赖包的 META-INF 下查找到这个配置属性, 可以通过 Option + Enter选择 Define configuration key ‘xxx’ 来创建配置, 其中包含了对应的名称, 类型, 描述等, 方便日后开发维护。
自动创建后的配置文件位于
resources/META-INF/additional-spring-configuration-metadata.json
reference
- https://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html
- https://blog.csdn.net/L_Sail/article/details/70342023
- https://blog.csdn.net/gybshen/article/details/117261037