> 文章列表 > 无聊小知识.03 Springboot starter配置自动提示

无聊小知识.03 Springboot starter配置自动提示

无聊小知识.03 Springboot starter配置自动提示

1、前言

Springboot项目配置properties或yaml文件时候,会有很多spring相关的配置提示。这个是如何实现的?如果我们自己的配置属性,能否也自动提示?

无聊小知识.03 Springboot starter配置自动提示

2、Springboot配置自动提示

其实IDE是通过读取配置信息的元数据而实现自动提示的。Springboot的元数据就在目录META-INF下。通过starter部分结构,我们可以看到如下:

无聊小知识.03 Springboot starter配置自动提示

其实,springboot自动提示元数据就在META-INF中的spring-configuration-metadata.json或additional-spring-configuration-metadata.json。

打开additional-spring-configuration-metadata.json可以看到json结构:

{"groups": [],"properties": [{"name": "spring.devtools.add-properties","type": "java.lang.Boolean","description": "Whether to enable development property defaults.","defaultValue": true}],"hints": []
}

properties:为设置的提示属性,name为属性名称,type为属性类型,defaultValue为该属性默认值,description为属性描述。

groups:为properties提供了一个有上下文关联的分组。本身并不指定一个值。

hints:为属性设置多个提示值。

具体配置描述详见官网地址:https://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html

无聊小知识.03 Springboot starter配置自动提示
无聊小知识.03 Springboot starter配置自动提示
无聊小知识.03 Springboot starter配置自动提示

3、手写尝试

1、创建starter工程

创建starter模块工程MySpringbootDemoModule1

无聊小知识.03 Springboot starter配置自动提示

2、自动装配

创建属性映射类,DemoProperties:

package org.example;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;@EnableConfigurationProperties({DemoProperties.class})
@ConfigurationProperties(prefix = "org.shamee")
public class DemoProperties {private String name;private Integer age;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}
}

创建MyAutoConfiguration:

package org.example;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MyAutoConfiguration {@Beanpublic DemoProperties demoProperties(){return new DemoProperties();}}

配置spring.factories:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\
org.example.MyAutoConfiguration

到此,一个简单的starter模块就已创建完毕,但是此时,如果直接使用,IDE是无法自动提示的。这里我们期望IDE帮我们自动提示DemoProperties中的两个属性,org.shamee.name和org.shamee.age。

3、创建元数据

那么,我们在resources下创建META-INF/additional-spring-configuration-metadata.json,并给与配置信息。

{"properties": [{"name": "org.shamee.name","type": "java.lang.String","defaultValue": "test"},{"name": "org.shamee.age","type": "java.lang.Integer","defaultValue": 12}]
}
无聊小知识.03 Springboot starter配置自动提示

4、安装使用

到此,就已经完成了一个能够让IDE自动帮我们提示的starter依赖。执行mvn install安装。

5、使用

创建一个主工程:MySpringbootDemo

无聊小知识.03 Springboot starter配置自动提示

pom.xml添加上述starter依赖。

刷新以来后,尝试application.properties上配置我们自定义的属性。

无聊小知识.03 Springboot starter配置自动提示

可以看到,IDE已经自动帮我们提示了属性名称以及默认的值。嗯,爽了。

看下starter依赖结构:

无聊小知识.03 Springboot starter配置自动提示

好了,又白嫖了一个无聊的小知识!!!😃😃😃