Apache

Extend Write a plugin or extension

Holds for
Not yet checked against Maven 3.9, 3.10 and 4.0
Source
Edit this page
Wrong?
Report a problem

Custom Toolchains

You can create custom toolchains to use with standard plugins (such as the maven-compiler-plugin) or with custom plugins.

A full working sample is included in the maven-toolchains-plugin integration tests, which are part of the plugin source tree:

  • src/it/setup-custom-toolchain holds the custom toolchain and plugin,
  • src/it/use-custom-toolchain holds a sample project using the toolchain through its plugin.

Creating a Custom Toolchain

A toolchain consists of:

Creating a Plugin Using a Toolchain

To find a tool, a plugin uses the ToolchainManager API to load the toolchain, then uses that toolchain object to find the tool's path:

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

private final ToolchainManager toolchainManager;

@Inject
public MyMojo(ToolchainManager toolchainManager) {
    this.toolchainManager = toolchainManager;
}

public void execute() throws MojoExecutionException {
    // get the custom toolchain
    CustomToolchain toolchain = (CustomToolchain) toolchainManager.getToolchainFromBuildContext("custom", session);

    if (toolchain == null) {
        throw new MojoExecutionException(
                "Could not find 'custom' toolchain: please check maven-toolchains-plugin configuration.");
    }

    getLog().info("Found 'custom' toolchain in build context.");

    // get a tool from the toolchain
    String path = toolchain.findTool("tool");

    getLog().info("Found expected tool named 'tool' at following location: " + path);
}

This code uses Maven Plugin Tool Annotations.

Using the Custom Toolchain and its Plugin

The custom toolchain implementation needs to be shared between the toolchain-aware plugin and maven-toolchains-plugin. This is done using a Maven extension:

  • if the toolchain is packaged with the plugin, declare the plugin as an extension:

    <plugin>
      <groupId>...</groupId>
      <artifactId>...</artifactId>
      <version>...</version>
      <extensions>true</extensions><!-- to share the custom toolchain with maven-toolchains-plugin -->
    </plugin>
    
  • if the toolchain is packaged separately, to be shared by multiple plugins, declare it as a build extension:

    <project>
      <build>
        <extensions>
          <extension>
            <groupId>...</groupId>
            <artifactId>...</artifactId>
            <version>...</version>
          </extension>
        </extensions>
      </build>
    </project>
    

Packaging a toolchain in its own artifact separate from the plugin is only useful when there are multiple plugins using the toolchain. If a custom toolchain will only be used by one plugin (possibly providing multiple goals), it is simpler to package the toolchain with the plugin in a single artifact.