使用Spring Boot的时候,填写配置信息(application.properties或application.yml)时,会出现提示。这种方式IDE也可以检查配置是否正确,对用户非常友好。本文介绍如何实现自定义配置的提示
使用注解@ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "blog")
public class BlogProperty {
/**
* blog's title
*/
private String title;
private String author;
private boolean gender;
private String national;
}
为配置类BlogProperty
添加注解@ConfigurationProperties
后,IDEA会出现红色提示Spring Boot Configuration Annotation Processor not found in classpath
,这是因为还需要为注解配置处理器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
Re-run Spring Boot Configuration Annotation Processor to update generated metadata
。该提示只是告诉我们去重新编译Spring Boot这样就可以更新生成的metadata文件,直接隐藏即可classes/META-INF/spring-configuration-metadata.json
{
"groups": [
{
"name": "blog",
"type": "com.tenmao.property.BlogProperty",
"sourceType": "com.tenmao.property.BlogProperty"
}
],
"properties": [
{
"name": "blog.author",
"type": "java.lang.String",
"sourceType": "com.tenmao.property.BlogProperty"
},
{
"name": "blog.gender",
"type": "java.lang.Boolean",
"sourceType": "com.tenmao.property.BlogProperty",
"defaultValue": false
},
{
"name": "blog.national",
"type": "java.lang.String",
"sourceType": "com.tenmao.property.BlogProperty"
},
{
"name": "blog.title",
"type": "java.lang.String",
"description": "blog's title",
"sourceType": "com.tenmao.property.BlogProperty"
}
],
"hints": []
}
配置提示
在自动生成的结果中再进行手动修改,比如为blog.national
提供枚举值
"hints": [
{
"name": "blog.national",
"values": [
{
"value": "China",
"description": "People's Republic of China"
},
{
"value": "Japan",
"description": "Japan in Asia"
}
]
}
]
枚举值
@EnableConfigurationProperties
:实际上并不需要