前言
spring boot在工作中是用到的越來越廣泛了,簡(jiǎn)單方便,有了它,效率提高不知道多少倍。spring boot配置文件對(duì)spring boot來說就是入門和基礎(chǔ),經(jīng)常會(huì)用到,所以寫下做個(gè)總結(jié)以便日后查看。
下面話不多說了,來一起看看詳細(xì)的介紹吧
1.配置文件
當(dāng)我們構(gòu)建完spring boot項(xiàng)目后,會(huì)在resources目錄下給我們一個(gè)默認(rèn)的全局配置文件 application.properties,這是一個(gè)空文件,因?yàn)閟pring boot在底層已經(jīng)把配置都給我們自動(dòng)配置好了,當(dāng)在配置文件進(jìn)行配置時(shí),會(huì)修改springboot自動(dòng)配置的默認(rèn)值。
配置文件名是固定的
- application.properties
但我們可以修改為
- application.yml
這兩個(gè)文件本質(zhì)是一樣的,區(qū)別只是其中的語(yǔ)法略微不同。
2.值的寫法
application.properties 配置文件比較簡(jiǎn)單,形式如下
- key = value
application.yml 配置文件使用ymal語(yǔ)言,ymal不是如xml般的標(biāo)記語(yǔ)言,更適合作為配置文件。
下面說下對(duì)于不同類型(字符串、數(shù)組)如何去規(guī)范書寫。
2.1 數(shù)字,字符串,布爾
1、直接寫
1
|
name=zhangsan |
2、雙引號(hào)
不會(huì)轉(zhuǎn)義字符串里面的特殊字符,特殊字符會(huì)作為本身想表示的意思
1
|
name: "zhangsan \n lisi" |
輸出:
zhangsan
lisi
3、單引號(hào)
會(huì)轉(zhuǎn)義特殊字符,特殊字符最終只是一個(gè)普通的字符串?dāng)?shù)據(jù)
1
|
name: ‘zhangsan \n lisi' |
輸出:
zhangsan \n lisi
2.2 對(duì)象、map(屬性和值)(鍵值對(duì))
例如配置類中的字段為
1
|
map<string,string> maps; |
在yml配置文件中,行內(nèi)寫法
1
|
person.maps: {key1: value1,key2: value2} |
需要注意:號(hào)后的空格,或者
1
2
3
|
person: maps: key: value |
在properties配置文件中
1
|
person.maps.key=value |
2.3 數(shù)組(list、set)
在yml配置文件中
1
2
3
4
5
|
person: list: - 1 - 2 - 3 |
行內(nèi)寫法
1
2
|
person: list: [ 1 , 2 , 3 ] |
在properties配置文件中
1
2
3
|
person.list[ 0 ]= 1 person.list[ 1 ]= 2 person.list[ 2 ]= 3 |
3.自定義配置屬性
spring boot提供自定義配置組件,拿前面舉例的屬性來寫一個(gè)規(guī)范的配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
@component // 或者@configuration @configurationproperties (prefix = "person" ) public class person { private map<string,string> maps; private list<string> list; private string name; public map<string, string> getmaps() { return maps; } public void setmaps(map<string, string> maps) { this .maps = maps; } public list<string> getlist() { return list; } public void setlist(list<string> list) { this .list = list; } public string getname() { return name; } public void setname(string name) { this .name = name; } } |
@configurationproperties 注解向spring boot聲明該類中的所有屬性和配置文件中相關(guān)的配置進(jìn)行綁定。
- prefix = "person":聲明配置前戳,將該前戳下的所有屬性進(jìn)行映射。
@component 或者@configuration:將該組件加入spring boot容器,只有這個(gè)組件是容器中的組件,配置才生效。
4.配置自動(dòng)提示
在配置自定義屬性時(shí),如果想要獲得和配置spring boot屬性自動(dòng)提示一樣的功能,則需要加入下面的依賴:
1
2
3
4
5
6
|
<!--導(dǎo)入配置文件處理器,配置文件進(jìn)行綁定就會(huì)有提示--> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-configuration-processor</artifactid> <optional> true </optional> </dependency> |
若是依舊無法自動(dòng)提示,可以嘗試開啟ide的annonation processing
5.配置屬性校驗(yàn)
自定義配置文件時(shí),可以使用@validated注解對(duì)注入的值進(jìn)行一些簡(jiǎn)單的校驗(yàn),示例代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@validated @configuration @configurationproperties (prefix = "person" ) public class person { @email private string mail; public string getmail() { return mail; } public void setmail(string mail) { this .mail = mail; } } |
@email 注解會(huì)對(duì)mail字段的注入值進(jìn)行檢驗(yàn),如果注入的不是一個(gè)合法的郵件地址則會(huì)拋出異常。
其它常見注解:
- @assertfalse 校驗(yàn)false
- @asserttrue 校驗(yàn)true
- @decimalmax(value=,inclusive=) 小于等于value,inclusive=true,是小于等于
- @decimalmin(value=,inclusive=) 與上類似
- @max(value=) 小于等于value
- @min(value=) 大于等于value
- @notnull 檢查null
- @past 檢查日期
- @pattern(regex=,flag=) 正則
- @size(min=, max=) 字符串,集合,map限制大小
- @validate 對(duì)po實(shí)體類進(jìn)行校驗(yàn)
上述的這些注解位于javax.validation.constraints包下,具體用法查看注釋即可了解。
6.自定義配置文件
除了在默認(rèn)的application文件進(jìn)行屬性配置,我們也可以自定義配置文件,例如新建 peoson.properties ,配置內(nèi)容如下
1
|
person.mail=yster @foxmail .com |
然后在配置類中使用@propertysource注解注入該配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@configuration @configurationproperties (prefix = "person" ) @propertysource (value = "classpath:person.properties" ) public class person { private string mail; public string getmail() { return mail; } public void setmail(string mail) { this .mail = mail; } } |
測(cè)試@propertysource注解不支持注入yml文件。
擴(kuò)展: @importresource:該注解導(dǎo)入spring的xml配置文件,讓配置文件里面的內(nèi)容生效。
例如: @importresource(locations = {"classpath:beans.xml"})
7.配置文件占位符
spring boot配置文件支持占位符,一些用法如下
7.1 隨機(jī)數(shù)
1
2
3
4
5
|
${random.value} ${random. int } ${random. long } ${random. int ( 10 )} ${random. int [ 1024 , 65536 ]} |
7.2 默認(rèn)值
占位符獲取之前配置的值,如果沒有可以是用:指定默認(rèn)值
1
2
3
4
5
6
7
8
9
|
person.last-name=張三${random.uuid} person.age=${random. int } person.birth= 2017 / 12 / 15 person.boss= false person.maps.k1=v1 person.maps.k2= 14 person.lists=a,b,c person.dog.name=${person.hello:hello}_dog person.dog.age= 15 |
8.多配置文件
8.1 多profile文件
我們?cè)谥髋渲梦募帉懙臅r(shí)候,文件名可以是 application-{profile}.properties/yml
默認(rèn)使用application.properties的配置
8.2 yml支持多文檔塊方式
通過---可以把一個(gè)yml文檔分割為多個(gè),并可以通過 spring.profiles.active 屬性指定使用哪個(gè)配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
server: port: 8081 spring: profiles: active: prod #指定使用哪個(gè)環(huán)境 --- server: port: 8083 spring: profiles: dev #指定屬于哪個(gè)環(huán)境 --- server: port: 8084 spring: profiles: prod #指定屬于哪個(gè)環(huán)境 |
8.3 激活指定profile
無論是使用上述多文檔塊的方式,還是新建application-dev.yml文件,都可以在配置文件中指定 spring.profiles.active=dev 激活指定的profile,或者
1、使用命令行:
1
|
java -jar spring-boot- 02 -config- 0.0 . 1 -snapshot.jar --spring.profiles.active=dev |
可以直接在測(cè)試的時(shí)候,配置傳入命令行參數(shù)
2、虛擬機(jī)參數(shù):
1
|
-dspring.profiles.active=dev |
9.配置文件加載位置
springboot 啟動(dòng)會(huì)掃描以下位置的application.properties或者application.yml文件作為spring boot的默認(rèn)配置文件
- –file:./config/
- –file:./
- –classpath:/config/
- –classpath:/
優(yōu)先級(jí)由高到底,高優(yōu)先級(jí)的配置會(huì)覆蓋低優(yōu)先級(jí)的配置;springboot會(huì)從這四個(gè)位置全部加載主配置文件。
項(xiàng)目打包好以后,我們可以使用命令行參數(shù)的形式,啟動(dòng)項(xiàng)目的時(shí)候來指定配置文件的新位置;指定配置文件和默認(rèn)加載的這些配置文件共同起作用形成互補(bǔ)配置;
我們還可以通過spring.config.location來改變默認(rèn)的配置文件位置,示例:
1
|
java -jar spring-boot-demo- 0.0 . 1 -snapshot.jar --spring.config.location=g:/application.properties |
10.外部配置加載順序
springboot也可以從以下位置加載配置,優(yōu)先級(jí)從高到低,高優(yōu)先級(jí)的配置覆蓋低優(yōu)先級(jí)的配置,所有的配置會(huì)形成互補(bǔ)配置。
1.命令行參數(shù)
所有的配置都可以在命令行上進(jìn)行指定
1
|
java -jar spring-boot- 02 -config- 02 - 0.0 . 1 -snapshot.jar --server.port= 8087 --server.context-path=/abc |
多個(gè)配置用空格分開,形如 --配置項(xiàng)=值
2.來自java:comp/env的jndi屬性
3.java系統(tǒng)屬性(system.getproperties())
4.操作系統(tǒng)環(huán)境變量
5.randomvaluepropertysource配置的random.*屬性值
由jar包外向jar包內(nèi)進(jìn)行尋找
優(yōu)先加載帶{profile}
6.jar包外部的application-{profile}.properties或application.yml(帶spring.profile)配置文件
7.jar包內(nèi)部的application-{profile}.properties或application.yml(帶spring.profile)配置文件
再來加載不帶profile
8.jar包外部的application.properties或application.yml(不帶spring.profile)配置文件
9.jar包內(nèi)部的application.properties或application.yml(不帶spring.profile)配置文件
10.@configuration注解類上的@propertysource
11.通過springapplication.setdefaultproperties指定的默認(rèn)屬性
11.自動(dòng)配置原理
11.1 自動(dòng)配置原理
1.springboot啟動(dòng)的時(shí)候加載主配置類,@enableautoconfiguration注解開啟了自動(dòng)配置功能。
2.@enableautoconfiguration 作用:
- 利用enableautoconfigurationimportselector給容器中導(dǎo)入一些組件
- 可以查看selectimports()方法的內(nèi)容;
- list<string> configurations = getcandidateconfigurations(annotationmetadata, attributes);獲取候選的配置
- springfactoriesloader.loadfactorynames()
掃描所有jar包類路徑下 meta-inf/spring.factories
把掃描到的這些文件的內(nèi)容包裝成properties對(duì)象
從properties中獲取到enableautoconfiguration.class類(類名)對(duì)應(yīng)的值,然后把他們添加在容器中
將類路徑下 meta-inf/spring.factories 里面配置的所有enableautoconfiguration的值加入到了容器中
每一個(gè)這樣的 xxxautoconfiguration類都是容器中的一個(gè)組件,都加入到容器中,用他們來做自動(dòng)配置。
1
2
3
4
|
# auto configure org.springframework.boot.autoconfigure.enableautoconfiguration=\ org.springframework.boot.autoconfigure.admin.springapplicationadminjmxautoconfiguration,\ ...... |
3.對(duì)每一個(gè)自動(dòng)配置類進(jìn)行自動(dòng)配置功能。
4.以httpencodingautoconfiguration(http編碼自動(dòng)配置)為例解釋自動(dòng)配置原理;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
@configuration //表示這是一個(gè)配置類,以前編寫的配置文件一樣,也可以給容器中添加組件 @enableconfigurationproperties (httpencodingproperties. class ) //啟動(dòng)指定類的configurationproperties功能;將配置文件中對(duì)應(yīng)的值和httpencodingproperties綁定起來;并把httpencodingproperties加入到ioc容器中 @conditionalonwebapplication //spring底層@conditional注解(spring注解版),根據(jù)不同的條件,如果滿足指定的條件,整個(gè)配置類里面的配置就會(huì)生效;判斷當(dāng)前應(yīng)用是否是web應(yīng)用,如果是,當(dāng)前配置類生效 @conditionalonclass (characterencodingfilter. class ) //判斷當(dāng)前項(xiàng)目有沒有這個(gè)類characterencodingfilter;springmvc中進(jìn)行亂碼解決的過濾器; @conditionalonproperty (prefix = "spring.http.encoding" , value = "enabled" , matchifmissing = true ) //判斷配置文件中是否存在某個(gè)配置 spring.http.encoding.enabled;如果不存在,判斷也是成立的 //即使我們配置文件中不配置pring.http.encoding.enabled=true,也是默認(rèn)生效的; public class httpencodingautoconfiguration { //他已經(jīng)和springboot的配置文件映射了 private final httpencodingproperties properties; //只有一個(gè)有參構(gòu)造器的情況下,參數(shù)的值就會(huì)從容器中拿 public httpencodingautoconfiguration(httpencodingproperties properties) { this .properties = properties; } @bean //給容器中添加一個(gè)組件,這個(gè)組件的某些值需要從properties中獲取 @conditionalonmissingbean (characterencodingfilter. class ) //判斷容器沒有這個(gè)組件 public characterencodingfilter characterencodingfilter() { characterencodingfilter filter = new orderedcharacterencodingfilter(); filter.setencoding( this .properties.getcharset().name()); filter.setforcerequestencoding( this .properties.shouldforce(type.request)); filter.setforceresponseencoding( this .properties.shouldforce(type.response)); return filter; } |
根據(jù)當(dāng)前不同的條件判斷,決定這個(gè)配置類是否生效。
一但這個(gè)配置類生效,這個(gè)配置類就會(huì)給容器中添加各種組件,這些組件的屬性是從對(duì)應(yīng)的properties類中獲取的,這些類里面的每一個(gè)屬性又是和配置文件綁定的。
5.所有在配置文件中能配置的屬性都是在xxxxproperties類中封裝者,配置文件能配置什么就可以參照某個(gè)功能對(duì)應(yīng)的這個(gè)屬性類
1
2
3
4
|
@configurationproperties (prefix = "spring.http.encoding" ) //從配置文件中獲取指定的值和bean的屬性進(jìn)行綁定 public class httpencodingproperties { public static final charset default_charset = charset.forname( "utf-8" ); |
精髓:
? 1)、springboot啟動(dòng)會(huì)加載大量的自動(dòng)配置類
? 2)、先看我們需要的功能有沒有springboot默認(rèn)寫好的自動(dòng)配置類
? 3)、再來看這個(gè)自動(dòng)配置類中到底配置了哪些組件(只要我們要用的組件有,我們就不需要再來配置了)
? 4)、給容器中自動(dòng)配置類添加組件的時(shí)候,會(huì)從properties類中獲取某些屬性。我們就可以在配置文件中指定這些屬性的值
xxxxautoconfigurartion:自動(dòng)配置類;給容器中添加組件;
xxxxproperties:封裝配置文件中相關(guān)屬性;
11.2 @conditional注解
@conditional派生注解(spring注解版原生的@conditional作用)
作用:必須是@conditional指定的條件成立,才給容器中添加組件,配置配里面的所有內(nèi)容才生效。
@conditional擴(kuò)展注解 | 作用(判斷是否滿足當(dāng)前指定條件) |
---|---|
@conditionalonjava | 系統(tǒng)的java版本是否符合要求 |
@conditionalonbean | 容器中存在指定bean; |
@conditionalonmissingbean | 容器中不存在指定bean; |
@conditionalonexpression | 滿足spel表達(dá)式指定 |
@conditionalonclass | 系統(tǒng)中有指定的類 |
@conditionalonmissingclass | 系統(tǒng)中沒有指定的類 |
@conditionalonsinglecandidate | 容器中只有一個(gè)指定的bean,或者這個(gè)bean是首選bean |
@conditionalonproperty | 系統(tǒng)中指定的屬性是否有指定的值 |
@conditionalonresource | 類路徑下是否存在指定資源文件 |
@conditionalonwebapplication | 當(dāng)前是web環(huán)境 |
@conditionalonnotwebapplication | 當(dāng)前不是web環(huán)境 |
@conditionalonjndi | jndi存在指定項(xiàng) |
自動(dòng)配置類必須在一定的條件下才能生效。
我們?cè)趺粗滥男┳詣?dòng)配置類生效?
我們可以通過在properties(yml)啟用 debug=true 屬性來讓控制臺(tái)打印自動(dòng)配置報(bào)告,這樣我們就可以很方便的知道哪些自動(dòng)配置類生效。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
============================ conditions evaluation report ============================ positive matches:(自動(dòng)配置類啟用的) ----------------- codecsautoconfiguration matched: - @conditionalonclass found required class 'org.springframework.http.codec.codecconfigurer' ; @conditionalonmissingclass did not find unwanted class (onclasscondition) codecsautoconfiguration.jacksoncodecconfiguration matched: - @conditionalonclass found required class 'com.fasterxml.jackson.databind.objectmapper' ; @conditionalonmissingclass did not find unwanted class (onclasscondition) ....... negative matches:(沒有啟動(dòng),沒有匹配成功的自動(dòng)配置類) ----------------- activemqautoconfiguration: did not match: - @conditionalonclass did not find required classes 'javax.jms.connectionfactory' , 'org.apache.activemq.activemqconnectionfactory' (onclasscondition) aopautoconfiguration: did not match: - @conditionalonclass did not find required classes 'org.aspectj.lang.annotation.aspect' , 'org.aspectj.lang.reflect.advice' , 'org.aspectj.weaver.annotatedelement' (onclasscondition) |
參考
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)服務(wù)器之家的支持。
原文鏈接:https://www.cnblogs.com/yueshutong/p/10025820.html