Like Share Discussion Bookmark Smile

J.J. Huang   2019-03-18   Spring Boot   瀏覽次數:次   DMCA.com Protection Status

SpringBoot - 第八章 | 配置說明(三)

Spring Boot 2.x 在對原本的配置屬性做了很多的改進,讓我們可以更簡單的使用這些配置。另外在本章節也會說明一些額外的配置文件的優先級、命令行參數配置、內部外部配置方式…等等。


配置文件

Spring Boot 2.x中對配置屬性加載的時候會除了像1.x版本時候那樣移除特殊字符外,還會將配置均用全小寫的方式進行匹配和加載。

1
2
3
4
spring.jpa.databaseplatform=mysql
spring.jpa.database-platform=mysql
spring.jpa.databasePlatform=mysql
spring.JPA.database_platform=mysql

以上四種配置方式都是相等的。

  • 撰寫DemoController來做驗證
  • 調整一下application.properties
1
2
3
4
spring.jpa.databaseplatform=mysql1
#spring.jpa.database-platform=mysql2
#spring.jpa.databasePlatform=mysql3
#spring.JPA.database_platform=mysql4

這邊為了驗證上方設置都是相等的,所以先把下面三個屬性註解,啟動應用後,輸入http://localhost:8080/ ,可以看到”mysql1”;接續測試後面三個,分別會取得”mysql2”、”mysql3”、”mysql4”。說明了這樣的配置都是相等的。
註:推薦使用全小寫配合-分隔符的方式來配置,例 spring.jpa.database-platform=mysql


配置文件的優先級

application.properties和application.yml文件可以放在一下四個位置

  1. 外部,在相對於應用程序運行目錄的/congfig子目錄裡 (file:./config/)
  2. 外部,在應用程序運行的目錄裡 (file:./)
  3. 內部,在config包內 (classpath:/config/)
  4. 內部,在Classpath根目錄 (classpath:/)

- 範例對應上面的路徑及配置內容為圖示:
路徑 參數/值
/chapter-8/config/application.properties test.priority=level1
/chapter-8/application.properties test.priority=level2
/chapter-8/src/main/resources/config/application.properties test.priority=level3
/chapter-8/src/main/resources/application.properties test.priority=level4
  • 範例圖片

  • 撰寫PriorityDemoController

啟動應用後,輸入http://localhost:8080/priority ,可以看到”Config: level1”
後續將application.properties裡面的test.priority.order照順序將其註解後,重新啟動應用,分別會取得”Config: level2”、”Config: level3”、”Config: level4”。


命令行參數配置

Spring Boot 是基於jar包執行的,打包jar的如列指令

1
java -jar xx.jar

而在這邊我們想要設定Tomcat的port,可以使用下列指令

1
java -jar xx.jar --server.port=9090

指令中連續的兩個–就是對application.properties中的屬性值進行賦值標誌。
java -jar xx.jar –server.port=9090 等於在application.properties中添加屬性server.port=9090。
註:Spring Boot 能從多重屬性源取得屬性,下面會介紹環境變數、系統屬性中取得屬性。


環境變數

在環境變數中通過小寫轉換與.替換_來對應配置文件中的內容,比如:環境變量SPRING_JPA_DATABASEPLATFORM=mysql的配置會產生與在配置文件中設置spring.jpa.databaseplatform=mysql一樣的效果。

  • 撰寫EnvDemoController

這邊的範例直接使用本機上面PATH的環境變數來做示範 (PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin)
啟動應用後,輸入http://localhost:8080/env ,可以看到”/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin”


系統屬性

系統屬性與文件配置中的類似,都以移除特殊字符並轉化小寫後實現綁定,比如下面的命令行參數都會實現配置spring.jpa.databaseplatform=mysql的效果

1
2
3
-Dspring.jpa.database-platform=mysql
-Dspring.jpa.databasePlatform=mysql
-Dspring.JPA.database_platform=mysql
  • 撰寫EnvDemoController
  • 設定VM arguments (-Dspring.test.env=testEnv)

  • Tomcat Web Modules

這邊使用Tomcat啟動,設定VM arguments 新增 -Dspring.test.env=testEnv 參數
啟動應用後,輸入http://localhost:8080/springboot-chapter8/env/test ,可以看到”testEnv”


屬性的讀取

上面介紹了Spring Boot 2.x中對屬性綁定的內容,可以看到對於一個屬性我們可以有多種不同的表達,但是如果我們要在Spring應用程序的environment中讀取屬性的時候,每個屬性的唯一名稱符合如下規則

  • 通過.分離各個元素
  • 最後一個.將前綴與屬性名稱分開
  • 必須是字母(a-z)和數字(0-9)
  • 必須是小寫字母
  • 用連字符-來分隔單詞
  • 唯一允許的其他字符是[和],用於List的索引
  • 不能以數字開頭

註:以上參考了
程序猿DD-翟永超Spring Boot 2.0 新特性(一):配置绑定 2.0 全解析 文章。