Maven Invoker - Using MVNW

Solution 1:

It's possible

Although the creators of the plugin seem not to support that aspect directly, you can configure the Maven Invoker API to run Maven Wrapper using the Invoker's methods setMavenExecutable and setMavenHome. There are two ways to achieve this:

  1. Using an absolute path of the Maven Wrapper script

    Invoker invoker = new DefaultInvoker();
    invoker.setMavenHome(Path.of(".").toFile());
    
    invoker.setMavenExecutable(new File("/home/user/projects/sample/mvnw"));
    
  2. Using a relative path of the Maven Wrapper script

    Invoker invoker = new DefaultInvoker();
    invoker.setMavenHome(Path.of(".").toFile());
    
    invoker.setMavenExecutable(new File("../mvnw"));
    

You can set the executable without any problem if MVNW script's path is absolute.

When it's relative then the internals of the plugin will try to prepend the <M2_HOME>/bin/ path - you have to skip (../) one parent folder when declaring the executable location (so the final path seen by the plugin will look like <M2_HOME>/bin/../mvnw).

As for M2_HOME - you have to set it via the API as well because of the plugin requirements. If you won't configure it, an exception will be raised:

Maven application directory was not specified, and ${maven.home} is not provided in the system properties. Please specify at least on of these.

Thankfully, you can safely set it to your project directory because since Maven 3.5.0 M2_HOME env is not necessary anymore.

If your MVNW script is not placed in the main directory of the project, you have to configure the paths appropriately.

While writing this answer I was using maven-invoker:3.0.1.