Maven專案Profile最佳實踐
阿新 • • 發佈:2020-08-27
Maven專案Profile打包最佳實踐
一、 背景
做專案的時候通常會有多個環境如:product、pre、test、dev,這個時候我們通常在專案中有5個配置檔案,application.properties存放公共的配置,每個環境要自己有獨自的配置檔案application-{profile}.properties,
問題:這麼多配置檔案,我們在執行的時候到底是用哪一個呢? 是在執行時區分還是在打包的時候區分開呢?
二、Profile簡介
1、Maven中引入Profile,以便構建專案的時候動態啟用某個Profile
- 可以打包的時候直接將啟用的Profile對應的配置檔案打包
- 可以將啟用的Profile對應的變數寫入到spring對應的配置檔案中,達到構建的時候指定環境,官方: https://maven.apache.org/plugins/maven-resources-plugin/resources-mojo.html
- 主配置檔案指定spring.profiles.active,如果沒有則載入預設的 application-default.properties
- 環境相關的配置檔案:application-{profile}.properties
- 官方載入順序說明:https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config
- 不同環境的配置檔案指定不同的日誌配置檔案:logging. config: classpath:logback-pre.xml
- springboot 打包指定的環境變數(spring.profiles.active=local)引數會用在2個地方:1) 載入對應環境的屬性檔案 2)變數會寫到Envement中,然後對映到屬性檔案配置的引數上如:spring.profiles.active=${spring.profiles.active}
- 檔案拷貝-根據打包指定的profile來打包對應的配置檔案-對應程式碼五中的1和2
- 變數佔位符:根據mvn指定的profile來過濾屬性檔案中的環境變數,對應程式碼五中的3
<profiles> <profile> <id>dev</id> <properties> <profiles.active>dev</profiles.active><!--開發環境 --> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>test</id> <properties> <profiles.active>test</profiles.active><!--測試環境 --> </properties> </profile> <profile> <id>prod</id> <properties> <profiles.active>prod</profiles.active><!--生產環境 --> </properties> </profile> </profiles>
- maven資源打包過濾
<resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <excludes> <exclude>application.properties</exclude> <exclude>application-dev.properties</exclude> <exclude>application-test.properties</exclude> <exclude>application-product.properties</exclude> </excludes> </resource> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>application.properties</include> <include>application-${profiles.active}.properties</include> </includes> </resource> </resources>3)屬性檔案指定環境 [email protected]@ 4)打包外掛
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> <configuration> <encoding>UTF-8</encoding> <overwrite>true</overwrite><!-- 目標檔案存在時覆蓋 --> </configuration> </plugin> </plugins>六、springboot啟動指定埠的集中方式:
- 第一配置檔案中新增server.port=7020
- 第二在命令列中指定啟動埠,比如傳入引數--server. port=6000java -jar bootServer. jar -- server.port=9000
- 第三傳入虛擬機器系統屬性java - Dserver.port=8000 -jar bootsample.jar
- 命令列指定的屬性,解析以後會放到 Environment這個類中: https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-application-property-files
- 屬性檔案application.properties會根據Environment中數值進行過濾