springboot-多環境配置


1創建基本項目

參考地址:springboot-hello world

接下來進行了三個測試,每個測試進行前需要把上一個測試產生的文件刪除

2 測試多個配置文件的優先級

2.1 創建四個application.yaml配置文件

application.yaml可以存在如下四個位置

2.1.1 file: ./config/

server.port: 8081

2.1.2 file: ./

server.port: 8082

2.1.3 classpath: /config/

server.port: 8083

2.1.4 classpath: /

server.port: 8084

2.2 通過ConfigApplication運行程序,查看啟動的端口號

第一次運行結果

說明 file: ./config/ 位置上的優先級最高,我們刪掉這個文件重新運行

說明 file: ./ 位置上的優先級第二高,我們刪掉這個文件重新運行

說明 classpath: /config/ 位置上的優先級第三,而 classpath: / 最低

2.3 結論

優先級排序: file: ./config/ > file: ./ > classpath: /config/ > classpath: /

3 測試使用properties文件切換環境

3.1 在resources目錄下創建兩個properties文件

3.1.1 application-test.properties

server.port=8081

3.1.2 application-dev.properties

server.port=8082

3.2 運行程序,查看端口號

沒有指定激活哪個配置文件,使用默認的配置.

3.3 創建application.properties

server.port=8083

3.2 重啟程序,查看端口號

使用了application.properties里面的配置

3.3 修改application.properties

通過修改application.properties來指定使用哪個文件的配置,注意 = 后面只需要跟 文件名稱中 application- 后面的內容即可

# springboot的多環境配置: 可以選擇激活哪一個配置文件
spring.profiles.active=test

3.4 重啟程序,查看端口號

使用了application-test.properties里面的配置

3.5 修改application.properties

# springboot的多環境配置: 可以選擇激活哪一個配置文件
spring.profiles.active=dev

3.6 重啟程序,查看端口號

使用了application-dev.properties里面的配置

4 測試使用yaml文件切換環境

4.1 在resources目錄下創建application.yaml文件

server:
  port: 8081

---
server:
  port: 8082
spring:
  profiles: dev

---
server:
  port: 8083
spring:
  profiles: test

4.2 啟動程序,查看端口號

使用了最上面的配置

4.3 修改application.yaml文件

server:
  port: 8081
spring:
  profiles:
    active: dev
---
server:
  port: 8082
spring:
  profiles: dev

---
server:
  port: 8083
spring:
  profiles: test

修改了文件最上面的代碼,指定了dev環境

4.4 重啟程序,查看端口號

使用了dev的配置

4.5 修改application.yaml文件

server:
  port: 8081
spring:
  profiles:
    active: test
---
server:
  port: 8082
spring:
  profiles: dev

---
server:
  port: 8083
spring:
  profiles: test

修改了文件最上面的代碼,指定了test環境

4.6 重啟程序,查看端口號

使用了test的配置,說明可以通過修改application.yaml最上面的代碼來切換配置環境


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM