默认激活配置文件

21

我正在使用Maven 3.0.3版本。我需要在脚本中定义一个变量("env")。 我的pom文件中有<profiles>部分,我会按照<profile>元素来定义这个变量...

<profile>
  <id>qa</id>
  <properties>
    <env>qa</env>
    ...
  </properties>
</profile>

在我的pom.xml文件中,如果没有通过"-P"命令行选项指定配置文件,则如何激活profile(并在变量未定义时设置变量)?我尝试了以下内容:
<profile>
  <id>dev</id>
  <activation>
    <activeByDefault>true</activeByDefault>
    <property>
      <name>env</name>
      <value>dev</value>
    </property>
  </activation>
  <properties>
    <url>http://localhost:8080/manager</url>
    <server>nnadbmon-dev-tomcat</server>
  </properties>
</profile>

但是运行命令“mvn compile”失败了,因为我设置的执行器插件需要我定义一个“env”变量。 这是我运行执行器插件的代码...

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-enforcer-plugin</artifactId>
  <version>1.0</version>
  <executions>
    <execution>
      <id>enforce-property</id>
      <goals>
        <goal>enforce</goal>
      </goals>
      <configuration>
        <rules>
          <requireProperty>
            <property>env</property>
            <message>Environment missing.  This should be either dev, qa, or prod, specified as part of the profile (pass this as a parameter after -P).</message>
            <regex>^(dev|qa|production)$</regex>
            <regexMessage>Incorrect environment.  Expecting one of dev, qa, or prod.</regexMessage>
          </requireProperty>
        </rules>
        <fail>true</fail>
      </configuration>
    </execution>
  </executions>
</plugin>

你的意思不是很清楚。你是想为“env”属性提供一个默认值吗? - bmargulies
是的,我想为 env 属性提供一个默认值。 - Dave
1
请发布您的执行器配置。实际上,您并没有定义“env”属性。您只需设置一个配置文件以运行,如果存在某个属性并具有特定值,则会发生这种情况。您可以向属性元素添加默认的env属性,并赋予其他值。 - bmargulies
嗨,我添加了我的执法者配置文件。不过我不理解你评论中的其他部分。如果上面的方式行不通,我该如何默认激活一个配置文件呢? - Dave
1
你为什么要使用执行器呢?只需将其设置为“activeByDefault”,然后取消执行器即可。 - bmargulies
2个回答

51

我知道这是很久以前的事情了,但我现在遇到了这个问题,所以...你应该这样做:

<profile>
    <id>dev</id>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
    <properties>
        <env>dev</env>
        <url>http://localhost:8080/manager</url>
        <server>nnadbmon-dev-tomcat</server>
    </properties>
</profile>

9
请注意:如果通过其他激活规则或-P命令行更积极地选择了任何其他配置文件,则activeByDefault配置文件将不会被选中。 - Greg Domjan
@GregDomjan 实际上,在我的情况下,我添加了 <activation> <property> <!-- 只需传递 -Dto-disable 以禁用配置文件 --> <name>to-disable</name> <value>!true</value> </property> </activation> 然后当我运行 mvn help:active-profiles 时,即使我使用 -Pmyprofile 等选项在命令行上传递其他配置文件,也可以看到该配置文件已默认激活。 - felix at housecat

0

嗨,我编辑了我的问题,包括我尝试过的内容(基本上是添加“<activeByDefault>true</activeByDefault>”),但是如果我省略“-P”指令,我的构建仍然会失败(因为执行程序插件找不到“env”属性)。如果您可以提供额外的信息和示例,将不胜感激。- Dave - Dave
1
@Dave 你可以输入 mvn help:active-profiles 命令来查看默认情况下哪些配置文件是激活的。 - Stephane

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接