Java Maven MOJO - getting information from project

2020-05-24 20:57发布

问题:

I am working on a maven plugin. I seem to have a hard time figuring out, what would be a good way to get POM information from project in which you execute the MOJO ?

For instance if I execute my mojo in another maven project I would like to get project name or some other parameters.

And one more thing, there is a context MAP in AbstractMojo.java class there is private Map pluginContext, could someone correct me if I am wrong but this is suppose to be used for passing information between mojos ?

回答1:

You can inject the current maven project into your mojo with a field declared like this:

/**
 * @parameter default-value="${project}"
 * @required
 * @readonly
 */
MavenProject project;

The projects name is then available by simply calling project.getName(). To use this API, you need to add the maven-project artifact as a dependency:

<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-project</artifactId>
    <version>2.0.6</version>
</dependency>


回答2:

@Component
private MavenProject project;

also works (more succinctly and intuitively) if using the new maven-plugin-annotations, which is the default for new mojos created from maven-archetype-plugin.

EDIT (thanks to @bmargulies): although the @Component Javadoc as of 3.2 suggests using it for MavenProject, apparently that is deprecated and the suggestion is dropped as of 3.3; the idiom suggested by maven-plugin-tools-annotations (as of 3.3) is something like this (both seem to work):

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


回答3:

The preferred syntax is now:

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

You will have to add a dependency for maven-project to your plugin's pom:

<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-project</artifactId>
    <version>2.0.6</version>
</dependency>

(Thanks to others who have supplied this information already. This answer combines them in one place.)