How to get ${basedir} value (or other properties) within the Mojo.execute()?
Asked Answered
C

1

6

I'm trying to get the value of the ${basedir} within a Mojo. I thought I could see that as a normal System property but

System.getProperty("basedir") 

returns null.

public void execute() throws MojoExecutionException, MojoFailureException {
    String baseDir = ???
}
Coeliac answered 11/9, 2015 at 13:45 Comment(0)
S
10

This is done by injecting the MavenProject and invoking the getBaseDir() method, like this:

public class MyMojo extends AbstractMojo {

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

    public void execute() throws MojoExecutionException, MojoFailureException {
        String baseDir = project.getBaseDir();
    }

}

The @Parameter is used to inject the value ${project}, which resolves to the current project being built from the Maven session.

Using annotations requires the following dependency on the Maven plugin:

<dependency>
  <groupId>org.apache.maven.plugin-tools</groupId>
  <artifactId>maven-plugin-annotations</artifactId>
  <version>3.5</version>
  <scope>provided</scope> <!-- annotations are needed only to build the plugin -->
</dependency>
Suspensoid answered 11/9, 2015 at 14:34 Comment(2)
Upvoted. @Component still works, but is now deprecated for MavenProject, should use @Parameter(defaultValue = "${project}", readonly = true). Thanks!Franko
@donsenior You're right, I edited with the non-deprecated method, and added some more explanation.Suspensoid

© 2022 - 2024 — McMap. All rights reserved.