3

spring-configuration-metadata.json文件是做啥的?

 2 years ago
source link: https://blog.didispace.com/spring-configuration-metadata-json/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

spring-configuration-metadata.json文件是做啥的?

在前几天分享的关于Spring Boot Starter中的spring.factories文件不再推荐使用的视频下,看到有网友问了这样一个问题:

这个文件也是位于/META-INF/目录下面:

图 2图 2

里面的大概是这样的:

{
"groups": [
{
"name": "swagger",
"type": "com.spring4all.swagger.SwaggerProperties",
"sourceType": "com.spring4all.swagger.SwaggerProperties"
},
{
"name": "swagger.authorization",
"type": "com.spring4all.swagger.SwaggerAuthorizationProperties",
"sourceType": "com.spring4all.swagger.SwaggerAuthorizationProperties"
},
{
"name": "swagger.contact",
"type": "com.spring4all.swagger.SwaggerProperties$Contact",
"sourceType": "com.spring4all.swagger.SwaggerProperties"
},
...
"properties": [
{
"name": "swagger.apply-default-response-messages",
"type": "java.lang.Boolean",
"description": "是否使用默认预定义的响应消息 ,默认 true",
"sourceType": "com.spring4all.swagger.SwaggerProperties",
"defaultValue": true
},
{
"name": "swagger.authorization.auth-regex",
"type": "java.lang.String",
"description": "需要开启鉴权URL的正则",
"sourceType": "com.spring4all.swagger.SwaggerAuthorizationProperties",
"defaultValue": "^.*$"
},
...

spring.factories的作用是让Spring Boot知道要加载这个Starter的哪些配置类,而这个文件又有啥用呢?

其实,之前我在Spring Boot教程中有具体讲过,这个内容是配置元数据。它的主要作用就是,当我们在配置文件中尝试编写配置信息的时候,IDE可以根据这个配置元数据给出了相关的提示信息,比如:

图 3图 3

所以,要做一个体验良好的Starter,这个文件还是非常重要的,对于使用你封装的开发者来说,写配置的时候就会方便很多。

如何自动生成?

既然spring.factories可以自动生成,那么spring-configuration-metadata.json文件可以自动生成吗?

答案是肯定的,不然维护这个json文件都会累死人!

你只需要在你的pom.xml中加入这个依赖:

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

一切就都搞定了,当你再次编译的时候,spring-configuration-metadata.json文件就自动出现啦!不过,这里还有个前提,你在写配置属性类的时候,有好好写注释,那么自动提示就都会带上了,比如下面这样:

@Data
@ConfigurationProperties("swagger")
public class SwaggerProperties {

/**
* 标题
**/
private String title = "";
/**
* 描述
**/
private String description = "";

本期视频已发布:https://www.bilibili.com/video/BV1L54y1o7rC/,欢迎关注我的B站!

好了,今天的分享就到这里!如果您学习过程中如遇困难?可以加入我们超高质量的Spring技术交流群,参与交流与讨论,更好的学习与进步!更多Spring Boot教程可以点击直达!,欢迎收藏与转发支持!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK