Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MavenProject injection does not seem to work

I try to write my own maven plugin, and I try to access the MavenProject with the usual annotation. However, when I execute the plugin the project field does not get injected and remains null. Here is my example code:

package xyz;

import org.apache.maven.plugin.*;
import org.apache.maven.plugins.annotations.*;
import org.apache.maven.project.*;

/**
 * @goal develop
 *
 */
public class Experiment extends AbstractMojo {

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

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        if (project == null) {
            getLog().error("Variable ${project} is null!");
        } else {
            getLog().info("Variable ${project} is filled!");
        }
    }
}

Whatever I try, I can't get it to work that maven automatically injects the project field with the proper object, I always get the information that the field is null. Any idea what I do wrong?

The pom file doesn't seem to be the interesting part here, because I get this behaviour with big poms I use for ages in my builds. But I can reproduce it even with the most simple possible pom file:

 <project>
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.mycompany.app</groupId>
   <artifactId>my-app</artifactId>
   <version>1</version>
 </project>
like image 429
Thorsten Avatar asked Nov 10 '22 10:11

Thorsten


1 Answers

Just in case someone drops onto this question: I had the same problem, the MavenProject was not injected with the annotaded property like this:

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

I had - guided by obviously pre-annotation mojo samples - defined the goal name with a Javadoc tag @goal as follows:

/**
 * execute my goal
 * @goal mygoal
 */
public class MyGoal extends AbstractMojo {
   // goal's code goes here
}

It all worked after changing this to using an annotation for the mojo class as follows:

@Mojo(name = "mygoal")
public class MyGoal extends AbstractMojo {
   // goal's code goes here
}

It seems to me as if maven only looks at annotations if the mojo is specified as an annotation. Mixing anotations (for fields) with Javadoc tags does not seem to work correctly (although I have not investigated this any further).

like image 138
Remigius Stalder Avatar answered Nov 15 '22 06:11

Remigius Stalder