簡介
springboot的application.properties或者.yml有對配置自動提示的功能,如果隨便寫一個不存在的配置,不僅沒有提示,而且會有警告,本文簡單介紹增加自己的配置的方法。
1.配置文件自動提示原理
spring插件在編寫配置的時候,自動掃描jar包中META-INF目錄下的spring-configuration-metadata.json文件,解析配置相關(guān)信息。
示例文件
{
"groups": [
{
"name": "demo",
"type": "com.example.demo.spring.boot.autoconfigure.DemoConfigurationProperties",
"sourceType": "com.example.demo.spring.boot.autoconfigure.DemoConfigurationProperties"
},
{
"name": "demo.session",
"type": "com.example.demo.config.Session",
"sourceType": "com.example.demo.spring.boot.autoconfigure.DemoConfigurationProperties",
"sourceMethod": "getSession()"
}
],
"properties": [
{
"name": "demo.enbale",
"type": "java.lang.String",
"description": "一級配置",
"sourceType": "com.example.demo.spring.boot.autoconfigure.DemoConfigurationProperties"
},
{
"name": "demo.session.session-cookie-key",
"type": "java.lang.String",
"description": "sessionId在cookie中存儲的key名",
"sourceType": "com.example.demo.config.Session",
"defaultValue": "session_token"
}
],
"hints": []
}
2.配置元數(shù)據(jù)json串含義解析
springboot可以自動提示的的配置,都是放在properties元素中,如果元素不是基本類型,需要在groups下聲明,description為該屬性的注釋,Tips:這個元數(shù)據(jù)json文件不需要手動編寫,可以自動生成。
3.定義自己的配置類
@ConfigurationProperties(prefix = "demo")
public class DemoConfigurationProperties {
/** 一級配置*/
private String name;
/** 引用外部類的配置,需要加@NestedConfigurationProperty注解*/
@NestedConfigurationProperty
private Session session = new Session();
Getter and Setter…
}
一般來說自己的配置類寫在com.company.xxproject.config包下,然后在com.company.xxproject.spring.boot.autoconfigure包下建一個xxprjectConfigurationProperties類,使用@ConfigurationProperties注解,引用config包下的具體項目配置用@NestedConfigurationProperty。
4.pom文件增加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
5.打包上傳
打包后,生成的jar包的META-INF文件下就會自動生成spring-configuration-metadata.json,其他項目引入該包之后,application配置文件就可以自動提示這些配置了