如何使用Maven执行程序?

时间:2010-03-18 18:23:26

标签: maven-2 maven-plugin

我想让Maven目标触发java类的执行。我正在尝试使用以下行迁移Makefile

neotest:
    mvn exec:java -Dexec.mainClass="org.dhappy.test.NeoTraverse"

我希望mvn neotest能够生成make neotest当前所做的事情。

exec plugin documentationMaven Ant tasks页面都没有任何直接的例子。

目前,我在:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.1</version>
  <executions><execution>
    <goals><goal>java</goal></goals>
  </execution></executions>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

但我不知道如何从命令行触发插件。

2 个答案:

答案 0 :(得分:134)

使用为exec-maven-plugin定义的全局配置

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4.0</version>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

在命令行上调用mvn exec:java将调用配置为执行类org.dhappy.test.NeoTraverse的插件。

因此,要从命令行触发插件,只需运行:

mvn exec:java

现在,如果您想在标准版本中执行exec:java目标,则需要将目标绑定到default lifecycle的特定阶段 。为此,请在phase元素中声明要绑定目标的execution

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <id>my-execution</id>
      <phase>package</phase>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

通过此示例,您的课程将在package阶段执行。这只是一个例子,根据您的需求进行调整。适用于插件版本1.1。

答案 1 :(得分:21)

为了执行多个程序,我还需要一个profiles部分:

<profiles>
  <profile>
    <id>traverse</id>
    <activation>
      <property>
        <name>traverse</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <configuration>
            <executable>java</executable>
            <arguments>
              <argument>-classpath</argument>
              <classpath/>
              <argument>org.dhappy.test.NeoTraverse</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

然后可以执行:

mvn exec:exec -Dtraverse