1創建基本項目
接下來進行了三個測試,每個測試進行前需要把上一個測試產生的文件刪除
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最上面的代碼來切換配置環境