項目開發中,都需要按不同環境進行不同的構建打包,最基本的就是把項目配置文件按環境打包:
- dev:開發環境
- test:測試環境
- preproduct:預發佈環境(上線前的預發佈服務器環境)
- product:生產環境
好像也無需解釋太多,需要用到 Maven Profile 的人,想必此功能的目的也是相當明確的。
一、Meven Profile 配置
主要是配置 pom.xml:
<project>
...
<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>product</id>
<properties>
<profiles.active>product</profiles.active>
</properties>
</profile>
</profiles>
...
</project>
其中 <activeByDefault>true</activeByDefault>
表示該 profile 默認激活。當然,<properties>
標籤中還可以按環境按需定義更多的屬性。
二、項目配置文件目錄規劃
我一般是:
src
....main
........java
........resource
............spring-context.xml
............other_common.properties
............profle
................dev
....................jdbc.properties
....................log.xml
................test
....................jdbc.properties
....................log.xml
................product
....................jdbc.properties
....................log.xml
上面這樣表示看起來有點雜,中心思想就是把公共的配置放在 src/main/resource 根目錄下,其他環境不同的配置,放在 src/main/resource/profile/${profiles.active}/目錄下。
三、Maven 資源路徑配置
<project>
...
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>profile/**</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/profile/${profiles.active}</directory>
</resource>
</resources>
</build>
...
</project>
說明:
- 第一個
<resource>
標籤,把 src/main/resources 目錄下所有配置包括進來,但是排除所有 profile/ 下的配置。 - 第二個
<resource>
標籤,把步驟一種激活的 ${profiles.active} 值的路徑下的配置文件包括進來,由此實現按環境構建。 - 注意:第二個
<resource>
標籤這樣配置, src/main/resources/profile/${profiles.active} 目錄下的配置文件會被構建打包到 src/main/resources 根目錄下。
四、構建打包
Maven Profile 構建打包命令:例如構建測試環境包:
# mvn clean package -Ptest
只需加 mvn 命令參數 -P 並加上步驟一中定義的 profile id 即可。如果要跳過測試:
# mvn clean package -DskipTests -Ptest
五、插曲:-DskipTests 和 -Dmaven.test.skip=true 區別
區別是:
- -DskipTests compiles the tests, but skips running them. 編譯測試用例,但是不執行。
- -Dmaven.test.skip=true skips compiling the tests and does not run them. 既不編譯測試用例,也不執行測試用例。”maven.test.skip is honored by Surefire, Failsafe and the Compiler Plugin”, 是萬無一失的、準不會有錯的。
- 參考:《What’s the difference between -DskipTests and -Dmaven.test.skip=true》&《Maven docs》
六、參考
先寫到這。