5

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 = ???
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Andrea
  • 2,714
  • 3
  • 27
  • 38

1 Answers1

8

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>
Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • Upvoted. `@Component` still works, but is now deprecated for `MavenProject`, should use `@Parameter(defaultValue = "${project}", readonly = true)`. Thanks! – Pablo Lascano Sep 29 '16 at 12:59
  • @donsenior You're right, I edited with the non-deprecated method, and added some more explanation. – Tunaki Sep 29 '16 at 13:45