Maven - 是否可以构建一个同时指定多个配置文件的项目?

Maven - Is it possible to build a project specifying multiple profiles simultaneously?

我们正在为仅使用 Web 服务的应用程序开发 Maven 原型。此原型提供三个配置文件,每个环境一个(开发、预、专业)。

关键是我们希望为那些将来可能需要它们的项目提供可选地包含 ORM 依赖项(JPA、Hibernate)的可能性。我们不得不创建一个包含这些依赖项的附加配置文件。

当我们构建项目时,我们使用 mvn package -Denvironment=dev。是否可以指定多个配置文件,例如:mvn package -Denvironment=dev,orm?

是的,这是可能的。但是您似乎首先对 how profiles are activated 感到困惑。

命令

mvn package -Denvironment=dev

不会激活任何配置文件而无需进一步配置。在您的情况下,它之所以有效,是因为您的 POM 中必须有一个配置文件定义,该配置文件定义由系统 属性 environment 的存在激活,值为 dev。您拥有的配置如下所示:

<profiles>
  <profile>
    <activation>
      <property>
        <name>environment</name>
        <value>dev</value>
      </property>
    </activation>
  </profile>
</profiles>

这是使配置文件在您通过系统 属性 和 -Denvironment 时激活的魔法。考虑到这一点,您可以使用相同的想法激活多个配置文件:声明多个 <profile> 元素,这些元素由系统 属性.

的存在激活
<profiles>
  <profile>
    <activation>
      <property>
        <name>myAwesomeProperty1</name>
        <value>true</value>
      </property>
    </activation>
  </profile>
  <profile>
    <activation>
      <property>
        <name>myAwesomeProperty2</name>
        <value>true</value>
      </property>
    </activation>
  </profile>
</profiles>

如果 myAwesomeProperty1myAwesomeProperty2 是系统 属性 且值为 true.

,则上述配置将激活两个配置文件

虽然在这种特殊情况下,您似乎想要根据您的环境激活构建,因此根据 -P 命令行开关激活配置文件可能是更好的主意,而不是系统 属性.

来自 Introduction to Build Profiles:

Profiles can be explicitly specified using the -P CLI option.

This option takes an argument that is a comma-delimited list of profile-ids to use. When this option is specified, the profile(s) specified in the option argument will be activated in addition to any profiles which are activated by their activation configuration or the <activeProfiles> section in settings.xml.

mvn groupId:artifactId:goal -P profile-1,profile-2

使用此解决方案,您可以使用多个配置文件 ID 调用 Maven。也就是说,如果你的配置中有

<profiles>
  <profile>
    <id>profile-1</id>
    <!-- rest of config -->
  </profile>
  <profile>
    <id>profile-2</id>
    <!-- rest of config -->
  </profile>
</profiles>

上述调用将同时激活 profile-1profile-2