1. 程式人生 > >Spring Boot 啟動(二) 配置詳解

Spring Boot 啟動(二) 配置詳解

ner sys 記錄 標準 () 系統屬性 code 不同 .profile

Spring Boot 啟動(二) 配置詳解

Spring 系列目錄(https://www.cnblogs.com/binarylei/p/10198698.html)

  1. Spring Boot 配置使用
  2. Spring Boot 配置文件加載流程分析 - ConfigFileApplicationListener

一、Spring Framework 配置

略...

二、Spring Boot 配置

2.1 隨機數配置

name.value=${random.int}
name.int=${random.int}
name.long=${random.long}
name.uuid=${random.uuid}
name.test1=${random.int(10)}
name.test2=${random.int[10,20]}

2.2 命令參數

java -jar xxx.jar --server.port=8080

2.3 多配置文件

applicaiton-dev.properties      # 開發環境
applicaiton-test.properties     # 測試環境
applicaiton-prod.properties     # 生產環境

配置文件關聯 profile 除了以上方式,還有另外兩種方式:

  • applicaiton-dev.properties 文件名指定剖面
  • applicaiton.properties && spring.profile=dev 文件內容配置 spring.profile
  • applicaiton-dev.properties && spring.profile=dev 文件名指定剖面且文件內容配置 spring.profile

2.4 Spring Boot 加載順序

  1. 命令行傳入的參數。
  2. SPRING_APPLICATION_JSON 中的屬性。 SPRING_APPLICATION_JSON 是以 JSON 格式配置在系統環境變量中的內容。
  3. java:comp/env 中的 JNDI 屬性。
  4. Java 的系統屬性,可以通過 System.getProperties() 獲得的內容操作。
  5. 系統的環境變量。
  6. 通過 random.* 配置的隨機屬性。
  7. 位於當前應用 jar 包之外,針對不同 {profile} 環境的配置文件內容,例如 application-{profile}.properties 或是 YAML 定義的配置文件。
  8. 位於當前應用 jar 包之內,針對不同 {profi1e} 環境的配置文件內容,例如 application-{profile}.properties 或是 YAM 定義的配置文件。
  9. 位於當前應用 jar 包之外的 application.properties 和 YAML 配置內容。
  10. 位於當前應用 jar 包之內的 application.properties 和 YAML 配置內容。
  11. 在 @Configuration 註解修改的類中,通過 @PropertySource 註解定義的屬性。
  12. 應用默認屬性,使用 SpringApplication.setDefaultProperties 定義的內容。

以上配置屬性加載類如下:

  1. 第一項是在 prepareEnvironment -> configureEnvironment -> configurePropertySources 定義的 CommandLinePropertySource。
  2. 第二項是在 spring.factories 中定義的 SpringApplicationJsonEnvironmentPostProcessor 處理,也實現了 EnvironmentPostProcessor 接口,優先級高於 ConfigFileApplicationListener。
  3. 第三-五項是 Spring Framework 標準的屬性,初始化 Environment 時配置。
  4. 第六項是在 ConfigFileApplicationListener 中定義的 RandomValuePropertySource。
  5. 第七-十項是在 ConfigFileApplicationListener 中加載配置文件,也實現了 EnvironmentPostProcessor 接口。

每天用心記錄一點點。內容也許不重要,但習慣很重要!

Spring Boot 啟動(二) 配置詳解