如何获取 Maven 依赖项 JAR 的名称(非完整路径)作为 pom.xml 变量

How to get name of Maven dependency JAR (not full path) as a pom.xml variable

看起来可以将 path/to/a/dependency.jar 作为 Maven pom.xml 中的可扩展变量:参见 Can I use the path to a Maven dependency as a property? 您可以将表达式扩展为字符串,例如/home/pascal/.m2/repository/junit/junit/3.8.1/junit-3.8.1.jar.

我想要的而不是我本地 Maven 存储库中依赖项 JAR 的完整路径 只是 JAR 的裸名 , 例如 junit-3.8.1.jar.

例如,在我的 pom.xml 中,我希望能够使用像 ${maven.dependency.junit.junit.jar.name} 这样的值来扩展到 junit-3.8.1.jar

我可以这样做吗?如何做?

不,很抱歉,这是不可能的。所以,你有两个选择。 1)修改maven源码,贡献修改。 2)自己写插件。 我推荐第二种选择。编写插件并不难。作为一个哲学原理,select 一个经常使用的插件,其功能接近你想要完成的。阅读并理解代码,然后修改它来做你想要的。

因此,对于您的示例,您可以查看过滤器插件。 Ant 插件中还有一些有趣的语法。它允许您命名依赖项并将这些 jar 文件名放入嵌入式 Ant 脚本中。

祝你好运。 :-)

作为一种更实用的替代方法,您可以使用您正在使用的确切版本号分解并手动编码 属性 值。您不会经常切换版本号,对吧?这只是您要处理的一个罐子,对吧?

您可以使用maven-antrun-plugin 来获取依赖的文件名。 Ant 有一个 <basename> 任务,它从路径中提取文件名。如 Can I use the path to a Maven dependency as a property? 中所述,依赖项的完整路径名在 ant 中可用 ${maven.dependency.groupid.artifactid.type.path}。这使我们能够像这样使用 ant 任务提取文件名:

<basename file="${maven.dependency.groupid.artifactid.type.path}" property="dependencyFileName" />

这会将文件名存储在名为 dependencyFileName 的 属性 中。

为了使这个 属性 在 pom 中可用,需要启用 maven-antrun-plugin 的 exportAntProperties 配置选项。此选项仅在插件版本 1.8 后可用。

此示例显示用于检索 junit 依赖项的工件文件名的插件配置:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.8</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <configuration>
                <exportAntProperties>true</exportAntProperties>
                <tasks>
                    <basename file="${maven.dependency.junit.junit.jar.path}"
                                      property="junitArtifactFile"/>
                </tasks>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
    </executions>
</plugin>