Profile 定義建置生命週期中使用的環境變體,可根據作業系統、JDK 版本、資料庫類型等條件自動啟動,實現「一次配置,多環境構建」。
%M2_HOME%/conf/settings.xml:全域 Profile,影響該機器所有使用者與專案。${user.home}/.m2/settings.xml:使用者級 Profile,影響該使用者所有專案。pom.xml:專案級 Profile(最推薦),隨專案部署到倉庫,對下游建置可見。profiles.xml(與 pom.xml 同目錄):專案級 Profile,但不隨專案部署。優先順序:pom.xml > profiles.xml > user settings.xml > global settings.xml。
注意:只有 repositories、pluginRepositories、properties 可在 settings.xml/profiles.xml 定義;其他類型(dependencies、plugins、build 等)必須在 pom.xml 定義。
mvn groupId:artifactId:goal -P profileId-1,profileId-2
<activeProfiles>
<activeProfile>profile-1</activeProfile>
</activeProfiles>
在 <activation> 區塊設定條件:
<jdk>1.8</jdk>(符合 1.8.x 即啟動)。<property><name>debug</name></property> → mvn -Ddebug。<property><name>env</name><value>test</value></property> → mvn -Denv=test。<os><name>Windows 10</name><family>Windows</family><arch>x86_64</arch><version>10.0</version></os>。<file><missing>target/generated-sources/...</missing></file>。若 Profile 定義在 settings.xml,屬性(如 ${appserver.home})僅存在於該使用者環境,其他開發者建置會失敗。
解決:將 Profile 移至 pom.xml,或利用父專案 pluginManagement 統一管理路徑,子專案繼承即可。
若啟動條件為 -Denv=dev 或 dev-2,但執行時傳入 -Denv=production,則無 Profile 啟動,屬性 ${appserver.home} 無法解析。
解決:提供預設 Profile(無 activation 或 activeByDefault>true</activeByDefault>),或使用 mvn help:active-profiles 診斷。
mvn help:active-profiles
mvn help:active-profiles -Denv=dev
mvn help:active-profiles -P profileId
輸出範例:
The following profiles are active:
- appserverConfig-dev (source: pom)
- appserverConfig (source: settings.xml)
pom.xml 定義 Profile,確保可移植性。activation 自動適應環境,減少手動切換。help:active-profiles 驗證生效狀態。