自定义工具链

您可以使用插件创建自己的自定义工具链。

一个完整的工作示例包含在maven-toolchains-plugin ITs 中,它是插件源代码树的一部分:

  • 有关自定义工具链和插件,请参见src/it/setup-custom-toolchain ,
  • 有关通过其插件使用工具链的示例项目,请参见src/it/use-custom-toolchain

以下说明是对样本关键点的解释。

创建自定义工具链

工具链包括:

使用工具链创建插件

要获得配置的工具链,插件使用ToolchainManager API 来获取预期的工具链,然后是工具链中的一些工具:

    @Component
    private ToolchainManager toolchainManager;

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

    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 );
    }

此代码使用Maven 插件工具 Java 5 Annotations

使用自定义工具链及其插件

自定义工具链实现需要在 toolchain-aware 插件和maven-toolchains-plugin之间共享:这是使用 Maven 扩展完成的:

  • 如果工具链与插件一起打包,则通过将插件声明为扩展来完成:
          <plugin>
            <groupId>...</groupId>
            <artifactId>...</artifactId>
            <version>...</version>
            <extensions>true</extensions><!-- to share the custom toolchain with maven-toolchains-plugin -->
          </plugin>
    
  • 如果工具链是单独打包的,要由多个插件共享,则必须将其声明为构建扩展:
    <project>
      <build>
        <extensions>
          <extension>
            <groupId>...</groupId>
            <artifactId>...</artifactId>
            <version>...</version>
          </extension>
        </extensions>
      </build>
    </project>
    

请注意,仅当有多个插件使用该工具链时,将工具链与插件分开包装在其自己的工件中才有用。正如通常预期的那样,自定义工具链将仅由一个插件使用(最终提供多个目标),将工具链与插件打包在一个工件中更简单。