目錄
在研究spring boot源碼時,會在META-INF目錄下發現spring-configuration-metadata.json的文件,這個文件用於在配置文件中設置屬性值時具有提示功能。這個功能適用於spring boot 2.0以上。
屬性說明
groups
"groups"是高級別的節點,它們本身不指定一個值,但爲properties提供一個有上下文關聯的分組。例如,server.port
和server.servlet-path
屬性是server
組的一部分,@ConfigurationProperties註解指定的屬性前綴,會自動提示屬性名稱前綴。
注:不需要每個"property"都有一個"group",一些屬性可以以自己的形式存在。
- name group的全名,該屬性必須
- type group數據類型的類名。例如,如果group是基於一個被@ConfigurationProperties註解的類,該屬性將包含該類的全限定名。如果基於一個@Bean方法,它將是該方法的返回類型。如果該類型未知,則該屬性將被忽略
- description 一個簡短的group描述,用於展示給用戶,要.點結尾。如果沒有可用描述,該屬性將被忽略
- sourceType 來源類名。例如,如果組基於一個被@ConfigurationProperties註解的@Bean方法,該屬性將包含@Configuration類的全限定名,該類包含此方法。如果來源類型未知,則該屬性將被忽略
- sourceMethod 該組的方法的全名(包含括號及參數類型)。例如,被@ConfigurationProperties註解的@Bean方法名。如果源方法未知,該屬性將被忽略
"groups": [
{
"name": "server",
"type": "org.springframework.boot.autoconfigure.web.ServerProperties",
"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
},
{
"name": "spring.jpa.hibernate",
"type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate",
"sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties",
"sourceMethod": "getHibernate()"
}
...
]
properties
輸入屬性名稱時的提示,即在配置文件中輸入屬性值,會提示。
- name 屬性全名,格式爲小寫虛線分割的形式(jiuxian.name-en).必須要有的
- type 屬性數據類型,java.lang.Boolean。類型未知可忽略
- description 該屬性的描述
- sourceType 來源類型,例如,如果property來自一個被@ConfigurationProperties註解的類,該屬性將包括該類的全限定名。如果來源類型未知則該屬性會被忽略
- defaultValue 定義輸入時的默認值,只是提示,並不是真正的默認值,可忽略
- deprecated 是否廢棄 boolean 值
- level 級別 error,warning。waring表示屬性可用,可不用。error,表示屬性對預期的是無效的。
- reason 廢棄原因
- replacement 替代屬性,爲properties 全名
"properties": [
{
"name": "server.port",
"type": "java.lang.Integer",
"sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
},
{
"name": "spring.jpa.hibernate.ddl-auto",
"type": "java.lang.String",
"description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.",
"sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate"
}
...
]
hints
hints描述某個屬性的屬性值的可選提示。在輸入冒號(:)後的提示
- name 屬性全名,不能爲空
- values 可選的值
"hints": [
{
"name": "spring.jpa.hibernate.ddl-auto",
"values": [
{
"value": "none",
"description": "Disable DDL handling."
},
{
"value": "validate",
"description": "Validate the schema, make no changes to the database."
}
]
}
]
原理
註解解釋器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
需要的註解
- @ConfigurationProperties 配置屬性文件,需要指定前綴 prefix
- @EnableConfigurationProperties 啓用配置,需要指定啓用的配置類
- @NestedConfigurationProperty 當一個類中引用了外部類,需要在該屬性上加該註解
註解使用
@ConfigurationProperties(prefix="server")
public class ServerProperties {
private String name;
private Host host;
// ... getter and setters
public static class Host {
private String ip;
private int port;
// ... getter and setters
}
}
增加文件
META-INF/additional-spring-configuration-metadata.json
文件中定義groups,attributes,hints
參考