14.4.2 激活profile
为了尽可能方便用户,Maven支持很多种激活Profile的方式。
1.命令行激活
用户可以使用mvn命令行参数-P加上profile的id来激活profile,多个id之间以逗号分隔。例如,下面的命令激活了dev-x和dev-y两个profile:
$mvn clean install-Pdev-x,dev-y
2.settings文件显式激活
如果用户希望某个profile默认一直处于激活状态,就可以配置settings.xml文件的active-Profiles元素,表示其配置的profile对于所有项目都处于激活状态,如代码清单14-9所示。
代码清单14-9 settings文件显式激活profile
<settings>
……
<activeProfiles>
<activeProfile>dev-x</activeProfile>
</activeProfiles>
……
</settings>
9.5节就曾经用到这种方式默认激活了一个关于仓库配置的profile。
3.系统属性激活
用户可以配置当某系统属性存在的时候,自动激活profile,如代码清单14-10所示。
代码清单14-10 某系统属性存在时激活profile
<profiles>
<profile>
<activation>
<property>
<name>test</name>
</property>
</activation>
……
</profile>
</profiles>
可以进一步配置当某系统属性test存在,且值等于x的时候激活profile,如代码清单14-11所示。
代码清单14-11 某系统属性存在且值确定时激活profile
<profiles>
<profile>
<activation>
<property>
<name>test</name>
<value>x</value>
</property>
</activation>
……
</profile>
</profiles>
不要忘了,用户可以在命令行声明系统属性。例如:
$mvn clean install-Dtest=x
因此,这其实也是一种从命令行激活profile的方法,而且多个profile完全可以使用同一个系统属性来激活。
4.操作系统环境激活
Profile还可以自动根据操作系统环境激活,如果构建在不同的操作系统有差异,用户完全可以将这些差异写进profile,然后配置它们自动基于操作系统环境激活,如代码清单14-12所示。
代码清单14-12 基于操作系统环境激活profile
<profiles>
<profile>
<activation>
<os>
<name>Windows XP</name>
<family>Windows</family>
<arch>x86</arch>
<version>5.1.2600</version>
</os>
</activation>
……
</profile>
</profiles>
这里family的值包括Windows、UNIX和Mac等,而其他几项name、arch、version,用户可以通过查看环境中的系统属性os.name、os.arch、os.version获得。
5.文件存在与否激活
Maven能够根据项目中某个文件存在与否来决定是否激活profile,如代码清单14-13所示。
代码清单14-13 基于文件存在与否激活profile
<profiles>
<profile>
<activation>
<file>
<missing>x.properties</missing>
<exists>y.properties</exists>
</file>
</activation>
……
</profile>
</profiles>
6.默认激活
用户可以在定义profile的时候指定其默认激活,如代码清单14-14所示。
代码清单14-14 默认激活profile
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
……
</profile>
</profiles>
使用activeByDefault元素用户可以指定profile自动激活。不过需要注意的是,如果POM中有任何一个profile通过以上其他任意一种方式被激活了,所有的默认激活配置都会失效。
如果项目中有很多的profile,它们的激活方式各异,用户怎么知道哪些profile被激活了呢?maven-help-plugin提供了一个目标帮助用户了解当前激活的profile:
$mvn help:active-profiles
maven-help-plugin还有另外一个目标用来列出当前所有的profile:
$mvn help:all-profiles