在實際開發過程中 生產環境 和 測試環境 有可能是不一樣的,因此將生產中的配置和測試中的配置拆分開,是非常必要的;在 springboot 中也提供了配置文件拆分的方式。
這裏以生產中項名名稱不一致爲例,假設:
- 生產中的項目名爲:cmzf
- 測試中的項目名爲:springboot
- 端口同時爲:8080
application.yml
- 主配置文件:
application.yml
# 用來書寫生產和測試相同的的配置
spring:
profiles:
active: dev
server:
port: 8080 #生產和測試爲同一個端口
- 生產配置文件:
application-pord.yml
server:
servlet:
context-path: /cmfz
- 測試配置文件:
application-dev.yml
server:
servlet:
context-path: /springboot
yml 多文檔塊方式
server:
port: 8081
spring:
profiles:
active: prod
---
server:
port: 8083
spring:
profiles: dev
---
server:
port: 8084
spring:
profiles: prod #指定屬於哪個環境
application.properties
- 主配置文件:
application.properties
# 延遲加載
spring.main.lazy-initialization=true
# 使用測試環境配置
spring.profiles.active=dev
測試配置文件:application-dev.properties
server.servlet.context-path=/springboot
server.port=8989
生產配置文件:application-prod.properties
server.servlet.context-path=/cmfz
server.port=8080
激活指定 profile(3種方法)
1、在配置文件中指定 spring.profiles.active=dev
2、命令行:運行 jar 包時後面寫上:--spring.profiles.active=dev
java -jar hello_springboot-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;
可以直接在測試的時候,配置傳入命令行參數:
3、虛擬機參數;
-Dspring.profiles.active=dev
配置文件的加載位置
springboot 啓動會掃描以下幾個位置的 配置文件:
–file:./config/
–file:./
–classpath:/config/
–classpath:/
優先級由高到底,高優先級的配置會覆蓋低優先級的配置;
SpringBoot 會從這四個位置全部加載主配置文件;互補配置;
我們還可以通過 spring.config.location
來改變默認的配置文件位置;
項目打包好以後,我們可以使用命令行參數的形式,啓動項目的時候來指定配置文件的新位置;
指定配置文件和默認加載的這些配置文件共同起作用形成互補配置;
java -jar hello_springboot-0.0.1-SNAPSHOT.jar --spring.config.location=D:/application.properties