【问题标题】:Using Maven 'exec:exec' with Arguments使用带有参数的 Maven 'exec:exec'
【发布时间】:2013-02-07 10:47:08
【问题描述】:

我有一个配置为使用 Maven 构建和运行的项目。该项目依赖于平台特定的原生库,我使用找到的策略here 来管理这些依赖项。

本质上,特定平台的 .dll.so 文件被打包到一个 jar 中,并通过识别目标平台的分类器推送到 Maven 服务器。然后 maven-dependency-plugin 解压平台特定的 jar,并将本机库复制到目标文件夹。

通常我会使用mvn exec:java 来运行Java 程序,但exec:java 在与Maven 相同的JVM 中运行应用程序,这会阻止我修改类路径。由于必须将本机依赖项添加到类路径中,因此我不得不改用mvn exec:exec。这是pom的相关sn-p:

...
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2.1</version>
    <configuration>
        <executable>java</executable>
        <arguments>
            <argument>-Djava.library.path=target/lib</argument>
            <argument>-classpath</argument>
            <classpath />
            <argument>com.example.app.MainClass</argument>
        </arguments>
    </configuration>
</plugin>
...

这适用于应用程序的默认配置,但我希望能够在命令行中指定一些可选参数。理想情况下,我想做这样的事情:

mvn exec:exec -Dexec.args="-a <an argument> -b <another argument>"

不幸的是,指定 exec.args 变量会覆盖我在 pom 中的参数(这是设置类路径和运行应用程序所必需的)。有没有解决的办法?在命令行指定一些可选参数而不覆盖我在 pom 中的内容的最佳方法是什么?

【问题讨论】:

    标签: maven exec-maven-plugin


    【解决方案1】:

    我设法使用 Maven 环境变量为我的问题找到了一个相当优雅的解决方案。

    默认值在 pom 中定义为属性,并作为参数添加到 exec 插件中:

    ...
    <properties>
        <argumentA>defaultA</argumentA>
        <argumentB>defaultB</argumentB>
    </properties>
    ...
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <configuration>
            <executable>java</executable>
            <arguments>
                <argument>-Djava.library.path=${project.build.directory}/lib</argument>
                <argument>-classpath</argument>
                <classpath />
                <argument>com.example.app.MainClass</argument>
                <argument>-a</argument>
                <argument>${argumentA}</argument>
                <argument>-b</argument>
                <argument>${argumentB}</argument>
            </arguments>
        </configuration>
    </plugin>
    ...
    

    现在我可以像以前一样使用默认参数运行:

    mvn exec:exec
    

    我可以使用以下命令轻松覆盖命令行中每个参数的默认值:

    mvn exec:exec -DargumentA=alternateA -DargumentB=alternateB
    

    【讨论】:

    • 以及如何在 Java 代码中访问这些参数,我的意思是这一行:String[] args?
    • @zygimantus you want mvn exec:java -Dexec.mainClass="path.to.your.class" -Dexec.args="arg1 arg2" 这超出了原始问题的范围。
    【解决方案2】:

    我花了一些时间理解标签“”的含义。分享细节以造福社区。它将 pom.xml 中定义的依赖库添加到 JVM。更多详情请查看https://www.mojohaus.org/exec-maven-plugin/examples/example-exec-for-java-programs.html

    .... 如果指定为 exec.args 参数的一部分,特殊字符串 %classpath 将被 Maven 计算的项目类路径替换。 %modulepath 的计数相同

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      相关资源
      最近更新 更多