【问题标题】:Retrieve list of a module's dependencies with a maven plugin MOJO使用 maven 插件 MOJO 检索模块的依赖项列表
【发布时间】:2015-05-18 09:03:11
【问题描述】:

我正在开发一个使用javassist 的maven 插件。为了加载应该使用 javassist 操作的类,我必须手动设置类路径:

classPool.appendClassPath("/path/to/the/file.jar");

有没有办法检索当前运行 maven 插件的模块的所有依赖项列表?由于您可以使用 <dependencies/> 元素指定插件运行的模块的依赖关系,因此应该有某种方法可以在我的 MOJO 中检索它们。

示例:假设我有以下 pom.xml,其中定义了我的插件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>my-group-id</groupId>
        <artifactId>my-parent-artifact-id</artifactId>
        <version>0.4.1-SNAPSHOT</version>
    </parent>
    <artifactId>my-artifact-id</artifactId>

    <dependencies>
        <dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-math3</artifactId>
                <version>3.4</version>
            </dependency>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>my-group-id</groupId>
                <artifactId>my-maven-plugin</artifactId>
                <version>${project.version}</version>
                ...
            </plugin>
        </plugins>
    </build>
</project>

现在在我的my-maven-plugin MOJO 中,我想检索在模块的&lt;dependencies/&gt; 部分中声明的工件commons-math3 的文件位置。一般来说,我还想从父模块及其所有传递依赖项中检索&lt;dependencies/&gt;

【问题讨论】:

    标签: java maven classpath maven-plugin


    【解决方案1】:

    同时我自己也找到了解决方案:

    /**
     * @goal cmp
     * @phase verify
     */
    public class JApiCmpMojo extends AbstractMojo {
        /**
         * @parameter default-value="${project}"
         */
        private org.apache.maven.project.MavenProject mavenProject;
        ...
        private void setUpClassPathUsingMavenProject(JarArchiveComparatorOptions comparatorOptions) throws MojoFailureException {
            notNull(mavenProject, "Maven parameter mavenProject should be provided by maven container.");
            Set<Artifact> dependencyArtifacts = mavenProject.getDependencyArtifacts();
            for (Artifact artifact : dependencyArtifacts) {
                ...
            }
        }
    }
    

    您从容器中获得的MavenProject 实例具有getDependencyArtifacts() 方法。此集合中的每个工件都有一个方法 getFile(),它返回一个 java.io.File 对象。

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      相关资源
      最近更新 更多