How to get access to Maven's dependency hierarchy within a plugin

前端 未结 7 1655
生来不讨喜
生来不讨喜 2020-11-29 05:25

In my plugin I need to process the dependency hierarchy and get information (groupId, artifactId, version etc) about each dependency and if it was excluded. What is the best

7条回答
  •  时光取名叫无心
    2020-11-29 05:51

    Here is an up to date, Maven3 example on how to get all dependencies (including transitive) as well as have access to the files themselves (if you for instance need to add the paths to a classpath).

    // Default phase is not necessarily important.
    // Both requiresDependencyCollection and requiresDependencyResolution are extremely important however!
    @Mojo(name = "simple", defaultPhase = LifecyclePhase.PROCESS_RESOURCES, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME)
    public class SimpleMojo extends AbstractMojo {
      @Parameter(defaultValue = "${project}", readonly = true)
      private MavenProject mavenProject;
    
      @Override
      public void execute() throws MojoExecutionException, MojoFailureException {
        for (final Artifact artifact : mavenProject.getArtifacts()) {
          // Do whatever you need here.
          // If having the actual file (artifact.getFile()) is not important, you do not need requiresDependencyResolution.
        }
      }
    }
    

    Changing the parameters in the Mojo is a very important piece that I was missing. Without it, lines like the following:

    @Parameter(defaultValue = "${project.compileClasspathElements}", readonly = true, required = true)
    private List compilePath;
    

    Will only return the classes directory, not the path you expect.

    Changing the requiresDependencyCollection and requiresDependencyResolution to different values will allow you to change the scope of what you want to grab. The maven documentation can provide more detail.

提交回复
热议问题