首先簡單介紹下 Maven 的 profile 是什么。對于人來說,profile 是指人的肖像,輪廓,比如論壇里每個人注冊了帳號后,可以設(shè)置自己的 profile,放上照片,介紹等等。對于 Maven 來說又是怎樣呢?整個項目定義好了項目對象模型(POM),就像論壇為每個人提供了默認(rèn)的行為功能,如果我想改變我機器上的 POM 呢?這時就可以使用 profile。下面舉個例子:
- <profiles>
- <profile>
- <id>jdk16</id>
- <activation>
- <jdk>1.6</jdk>
- </activation>
- <modules>
- <module>simple-script</module>
- </modules>
- </profile>
- </profiles>
<profiles>
<profile>
<id>jdk16</id>
<activation>
<jdk>1.6</jdk>
</activation>
<modules>
<module>simple-script</module>
</modules>
</profile>
</profiles>
這個 profile 的意思是,當(dāng)機器上的 JDK 為1.6的時候,構(gòu)建 simple-script 這個子模塊,如果是1.5或者1.4,那就不構(gòu)建,這個 profile 是由環(huán)境自動激活的。
我們需要在合適的地方使用合適的 profile ,并且在合適的時候用合適的方式將其激活,你不能在構(gòu)建服務(wù)器上激活非公共的 profile,你也不能要求開發(fā)人員寫很復(fù)雜的命令來使用常規(guī)的 profile。因此這里介紹一下幾種 profile 的激活方式。
1. 根據(jù)環(huán)境自動激活。
如前一個例子,當(dāng) JDK 為1.6的時候,Maven 就會自動構(gòu)建 simple-script 模塊。除了 JDK 之外,我們還可以根據(jù)操作系統(tǒng)參數(shù)和 Maven 屬性等來自動激活 profile,如:
- <profile>
- <id>dev</id>
- <activation>
- <activeByDefault>false</activeByDefault>
- <jdk>1.5</jdk>
- <os>
- <name>Windows XP</name>
- <family>Windows</family>
- <arch>x86</arch>
- <version>5.1.2600</version>
- </os>
- <property>
- <name>mavenVersion</name>
- <value>2.0.5</value>
- </property>
- <file>
- <exists>file2.properties</exists>
- <missing>file1.properties</missing>
- </file>
- </activation>
- ...
- </profile>
<profile>
<id>dev</id>
<activation>
<activeByDefault>false</activeByDefault>
<jdk>1.5</jdk>
<os>
<name>Windows XP</name>
<family>Windows</family>
<arch>x86</arch>
<version>5.1.2600</version>
</os>
<property>
<name>mavenVersion</name>
<value>2.0.5</value>
</property>
<file>
<exists>file2.properties</exists>
<missing>file1.properties</missing>
</file>
</activation>
...
</profile>
2. 通過命令行參數(shù)激活。
這是最直接和最簡單的方式,比如你定義了一個名為 myProfile 的 profile,你只需要在命令行輸入 mvn clean install -Pmyprofile
就能將其激活,這種方式的好處很明顯,但是有一個很大的弊端,當(dāng) profile 比較多的時候,在命令行輸入這寫 -P 參數(shù)會讓人覺得厭煩,所以,如果你一直用這種方式,覺得厭煩了,可以考慮使用其它自動激活的方式。
3. 配置默認(rèn)自動激活。
方法很簡單,在配置 profile 的時候加上一條屬性就可以了,如:
- <profile>
- <id>dev</id>
- <activation>
- <activeByDefault>true</activeByDefault>
- </activation>
- ...
- </profile>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
...
</profile>
在一個特殊的環(huán)境下,配置默認(rèn)自動激活的 profile 覆蓋默認(rèn)的 POM 配置,非常簡單有效。
4. 配置 settings.xml 文件 profile 激活。
settings.xml 文件可以在 ~/.m2 目錄下,為某個用戶的自定義行為服務(wù),也可以在 M2_HOME/conf 目錄下,為整臺機器的所有用戶服務(wù)。而前者的配置會覆蓋后者。同理,由 settings.xml 激活的 profile 意在為用戶或者整個機器提供特定環(huán)境配置,比如,你可以在某臺機器上配置一個指向本地數(shù)據(jù)庫 URL 的 profile,然后使用該機器的 settings.xml 激活它。激活方式如下:
- <settings>
- ...
- <activeProfiles>
- <activeProfile>local_db</activeProfile>
- </activeProfiles>
- </settings>
<settings>
...
<activeProfiles>
<activeProfile>local_db</activeProfile>
</activeProfiles>
</settings>
Maven 提供的 profile 功能非常強大和靈活,用得好的話,可以有效的隔離很多特殊的配置,使得整個項目能在不同環(huán)境中順利的構(gòu)建。但是,強大和靈活帶來得問題是相對難掌握,希望本文能對 Maven 使用者有幫助。