一、背景
官方提供的spring boot starter的配置项,我们用IDE配置的时候一般都有自动提示的,如下图所示。
而我们自己自定义的配置却没有,对开发非常不友好容易打错配置,那这个是怎样实现的呢?
二、提示原理
IDE是通过读取配置信息的元数据而实现自动提示的,而元数据在目录META-INF
中的spring-configuration-metadata.json
或者additional-spring-configuration-metadata.json
三、实现自动提示
以我这个自己开发的starter中的自定义配置文件为例,如果自己手动创建这些元数据的话工作量比较大,使用IDEA
的话有自动生成功能
@Data
@EqualsAndHashCode(callSuper = true)
@Configuration
@ConfigurationProperties(prefix = "translation.baidu")
@ConditionalOnProperty(prefix = "translation", value = "baidu.enabled", havingValue = "true")
public class BaiduTranslationProperties extends BasicProperties {
/**
* app id
*/
private String appId;
/**
* securityKey
*/
private String securityKey;
}
3.1. 引入依赖spring-boot-configuration-processor
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
3.2. 编译项目
项目在重新编译后就会在META-INF自动生成spring-configuration-metadata.json
文件。
{
"groups": [
{
"name": "translation.baidu",
"type": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties",
"sourceType": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties"
},
{
"name": "translation.google",
"type": "com.vevor.tools.translation.config.properties.GoogleTranslationProperties",
"sourceType": "com.vevor.tools.translation.config.properties.GoogleTranslationProperties"
}
],
"properties": [
{
"name": "translation.baidu.app-id",
"type": "java.lang.String",
"description": "app id",
"sourceType": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties"
},
{
"name": "translation.baidu.enabled",
"type": "java.lang.Boolean",
"description": "是否开启",
"sourceType": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties"
},
{
"name": "translation.baidu.security-key",
"type": "java.lang.String",
"description": "securityKey",
"sourceType": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties"
},
{
"name": "translation.baidu.url",
"type": "java.lang.String",
"description": "设置域名地址",
"sourceType": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties"
},
{
"name": "translation.google.enabled",
"type": "java.lang.Boolean",
"description": "是否开启",
"sourceType": "com.vevor.tools.translation.config.properties.GoogleTranslationProperties"
},
{
"name": "translation.google.url",
"type": "java.lang.String",
"description": "设置域名地址",
"sourceType": "com.vevor.tools.translation.config.properties.GoogleTranslationProperties"
}
],
"hints": []
}