Maven:如何查询可执行类路径?

Maven: how to query the executable classpath?

我有一个带有一些指定依赖项的 Maven 项目。

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
</dependency>

我如何查询 Maven 以找出它用于这些依赖项的路径,或者我应该用于独立执行的类路径?

我的目标是构建一个包装器,它使用适当的类路径运行程序。

Maven 中有多种选择:

Maven 依赖插件(构建-class路径目标)

查看 Maven Dependency Plugin,尤其是 build-classpath 目标提供了完整的 class 外部执行使用路径。在众多选项中,outputFile 参数可能会有帮助。
使用不需要配置,运行

mvn dependency:build-classpath

在您的项目中,您会看到 class 路径作为构建输出的一部分。或者

mvn dependency:build-classpath -Dmdep.outputFile=classpath.txt

仅将 class 路径重定向到文件。

Maven 依赖插件(复制依赖目标)

要构建包装器,您还可以查看 copy-dependencies 目标,该目标会将所需的依赖项 (jars)(包括传递依赖项)复制到已配置的文件夹(因此您不需要硬编码路径到您的本地计算机)。
官方网站 here 上提供了插件配置示例。 比如下面的配置:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.10</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                        <includeScope>runtime</includeScope>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

将添加到文件夹 target/dependencies 范围 compile 中声明的所有依赖项。注意:关于链接的官方示例,我添加了 <includeScope>runtime</includeScope> 配置条目(根据 documentation 和我的测试,它将包括编译和 运行time 范围的依赖项),否则它会默认情况下还包括 test 范围(我相信您在 运行 时不需要)。

Exec Maven 插件(java 或 exec 目标)

或者,您可以使用 Exec Maven Plugin 使用所需的 class 路径从 Maven 执行 main
官方网站上提供了一个插件配置示例,here
以下配置为例:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1</version>
    <executions>
        <execution>
            <id>my-execution</id>
            <phase>package</phase>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <mainClass>com.sample.MainApp</mainClass>
    </configuration>
</plugin>

将通过 mvn exec:java 主 class MainApp 将 Exec 插件配置为 运行,显然具有所需的 class 路径。

Maven 程序集插件

最后,Maven Assembly Plugin also provides facilities to build an executable jar with dependencies, as explained here,在关于 Whosebug 的另一个问题中。