1. 程式人生 > >Spring boot 中通過profile屬性指定配置檔案

Spring boot 中通過profile屬性指定配置檔案

1、多Profile檔案

1 通過在配置檔案中配置

一個專案在開發的過程中可能存在搓個配置檔案一個是生產環境,一個是測試環境,那麼如何去指定呢?
我們知道在主配置檔案編寫的時候,檔名可以是 application-{profile}.properties/yml。

預設使用application.properties的配置;
我們建立兩個配置檔案application-dev.propertiesapplication-prod.properties進行一個簡單的埠測試

  • application-dev.properties
server.port=8082
  • application-prod.properties
server.port=8081
  • 我們通過預設的配置檔案application.properties進行指定
    spring.profiles.active
spring.profiles.active=prod
  • 啟動檢視結果

從啟動日誌中可以看到Tomcat started on port(s): 8081 (http) with context path '' 通過spring.profiles.active屬性配置成功

2 命令列的形式

當然我們也可以通過命令列的形式,把專案打成jar包,通過java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;在專案啟動的時候指定

或者我們也可以在idea中配置,如下圖;
–spring.profiles.active=dev
在這裡插入圖片描述

3 通過虛擬機器引數指定

-Dspring.profiles.active=prod
在這裡插入圖片描述

2、yml支援多文件塊方式

上面我們通過properties可以指定配置檔案,yml提供了一個更加簡單的形式,多文件塊。

在yml配置檔案中我們可以通過---來劃分多個塊就不用建立多個配置檔案也能達到效果。

  • application.yml
spring:
  profiles:
    active: dev

---
#測試環境

server:
  port: 8081
spring:
  profiles: prod
---
#成產環境

server:
  port: 8082
spring:
  profiles: dev

  • 啟動檢視結果

從啟動日誌中可以看到Tomcat started on port(s): 8082 (http) with context path ''