Churchill Nolan Churchill Nolan - 9 days ago 6
Java Question

How to use MavenBuildHelper in Maven mojo

I am developing a maven-plugin with multiple Mojos. In one of them, my goal is to attach additional artifact to my project. Similar to attach-artifact of maven-build-helper-plugin. But I don't want to use any given build plugin, I want to do it through my Mojo.

I know that I have to use MavenProjectHelper.attachArtifact. Because MavenProject.attachArtifact is deprecated.

What I have now is this (in the mojo.java):

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

@Parameter(defaultValue = "${helper}", required = true, readonly = true)
protected MavenProjectHelper projectHelper;


And in
execute
method:

projectHelper.attachArtifact(project, "plugin", file);


But the problem is,
MavenProjectHelper
's default value is not
${helper}
. Which is why, I get the following error:

Failed to execute goal com.company.product.repo:my-plugin:1.0.1:attach-artifact (default) on project consumer-plugin: The parameters 'projectHelper' for goal com.company.product.repo:my-plugin:1.0.1:attach-artifact are missing or invalid -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginParameterException


How do I give it the correct value? Like
MavenSession
's
${session}
, I have assumed that
MavenProjectHelper
has a default value. If so, what is it? If not, then how can I give the correct value to
MavenProjectHelper
parameter?

Answer

The MavenProjectHelper is a Plexus component, not a plugin parameter, and should be injected by annotating it with the @org.apache.maven.plugins.annotations.Component annotation:

Used to configure injection of Plexus components by MavenPluginManager.getConfiguredMojo(...).

Thus, you should have instead:

@Component
private MavenProjectHelper projectHelper;

This annotation, just like @Parameter, comes with the Plugin Tools for annotations, that you can declare in the POM of your Maven plugin with

<dependency>
  <groupId>org.apache.maven.plugin-tools</groupId>
  <artifactId>maven-plugin-annotations</artifactId>
  <version>3.5</version>
  <scope>provided</scope>
</dependency>

To clarify further, what you can inject with @Parameter is documented in the Javadoc of the PluginParameterExpressionEvaluator class (among others, session for the Maven session, project for the current Maven project or mojoExecution for the current Mojo execution).