11.5. Settings Profile

当一个项目需要为特定的环境自定义构建设置的时候,profile很有用,但是为什么一定要为所有Maven项目覆盖构建设置呢?比如为每个Maven构建添加一个需要访问的内部仓库。你可以使用一个settings profile做这件事情。项目profile关心于覆盖某个项目的配置,而settings profile可以应用到所有你使用Maven构建的项目。你可以在两个地方定义settings profile:定义在~/.m2/settings.xml中的用户特定settings profile,或者定义在${M2_HOME}/conf/settings.xml中的全局settings profile。这里是一个定义在~/.m2/settings.xml中的settings profile的例子,它为所有的构建设置了一些用户特定的配置属性。如下settings.xml文件为用户tobrien定义:

Example 11.7. 定义用户特定的Setting Profile (~/.m2/settings.xml)

<settings>
  <profiles>
    <profile>
      <id>dev</id>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <executions>
           <execution>
              <goals>
                 <goal>sign</goal>
              </goals>
           </execution>
        </executions>
        <configuration>
           <keystore>/home/tobrien/java/keystore</keystore>
           <alias>tobrien</alias>
           <storepass>s3cr3tp@ssw0rd</storepass>
           <signedjar>
         /data/hudson-temporal-data/hudson-orchestrator-home/workspace/Book-To-Production/content-zh/target/signed/book.jar
           </signedjar>
           <verify>true</verify>
        </configuration>
      </plugin>
    </profile>
  </profiles>
</settings>

前面的例子是一个对于用户特定settings profile的真实用例。该样例中,当发布时为一个JAR文件签名的时候,设置用户特定的信息如密码和别名。你不会希望将这些配置参数存储到项目共享的pom.xml或者profiles.xml文件中,因为它们包含了一些不应该被公开的私人信息。

settings profile的缺点是它们可能会干扰项目可移植性。如果前面的例子是一个开源项目,如果一个新的开发者没有和其它开发者交流过并手工配置了一个settings profile,他将不能够为一个JAR签名。这样的情况下,为JAR签名的安全需求就与全局可移植性构建产生了冲突。在大部分开源项目中,有一些任务需要安全证书:将一个构件发布到远程仓库,发布项目的web站点,或者为JAR文件签名。对于这些任务,可以达到的最高级别可移植性只能是组织可移植性。这些高安全性任务通常需要一些手工的profile安装和配置。

除了显式的使用-P命令行参数指定profile的名称。你还可以为所有构建的项目定义一个激活profile的列表。例如,如果你想要为每个项目激活定义在settings.xml中的dev profile,你可以在你的~/.m2/settings.xml文件中添加如下的设置:

Example 11.8. 定义激活的Settings Profile

<settings>
  ...
  <activeProfiles>
    <activeProfile>dev</activeProfile>
  </activeProfiles>
</settings>


该设置只会激活settings profile,不会激活id匹配的项目profile。例如,如果你有一个项目,在pom.xml中定义了一个iddev的profile,那个profile不会受你settings.xmlactiveProfile设置的影响。activeProfile设置只对你settings.xml文件中定义的profile有效。

11.5.1. 全局Settings Profile

如同用户特定的settings profile一样,你也可以在${M2_HOME}/conf/settings.xml中定义一组全局profile。在这个配置文件中定义的profile对所有使用该Maven安装的用户可用。如果你正为一个特定的组织创建一个定制的Maven分发包,并且你想要确保每个Maven用户使用一组构建profile以确保内部可移植性,定义全局settings profile就十分有用。如果你需要添加自定义插件仓库,或者定义一组只在你组织内部可用的自定义插件,你就可以为你的用户分发一个内置了这些配置的Maven。配置全局settings profile和配置用户特定的settings profile的方法完全一样。