Using maven 3, how to use project classpath in a p

2020-07-14 09:34发布

I'm writing a maven 3 plugin, for which I would like to use project classpath.

I've tried using the approach mentionned in Add maven-build-classpath to plugin execution classpath, but it seems the written component is not found by maven. (I have a ComponentNotFoundException at plugin execution start).

So, what is the "reference" way to use project classpath in a maven 3 plugin ? Or if the component way is the right one, is there any configuration step beside adding the component as configurator property of the @Mojo annotation ?

2条回答
叼着烟拽天下
2楼-- · 2020-07-14 10:02

You can retrieve the classpath elements on the MavenProject by calling:

A sample MOJO would be:

@Mojo(name = "foo", requiresDependencyResolution = ResolutionScope.TEST)
public class MyMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true, required = true)
    private MavenProject project;

    public void execute() throws MojoExecutionException, MojoFailureException {
        try {
            getLog().info(project.getCompileClasspathElements().toString());
            getLog().info(project.getRuntimeClasspathElements().toString());
            getLog().info(project.getTestClasspathElements().toString());
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoExecutionException("Error while determining the classpath elements", e);
        }
    }

}

What makes this work:

  • The MavenProject is injected with the @Parameter annotation using the ${project} property
  • requiresDependencyResolution will enable the plugin accessing the dependencies of the project with the mentioned resolution scope.
查看更多
\"骚年 ilove
3楼-- · 2020-07-14 10:11

Sometimes having a look at the code of a plugin which does exactly the same explains it a lot better. If there's one plugin which needs to know classpaths it's the maven-compiler-plugin (source). Just look for classpathElements.

查看更多
登录 后发表回答