概述

本篇以开发git pre commit check 插件为例,讲述如何开发maven插件

maven插件开发

新建maven项目

添加packaging

<packaging>maven-plugin</packaging>

添加依赖

  <dependencies>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
      <version>3.5.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven.plugin-tools</groupId>
      <artifactId>maven-plugin-annotations</artifactId>
      <version>3.5</version>
      <scope>provided</scope>
    </dependency><!---->
  </dependencies>

添加插件

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
      <source>1.8</source>
      <target>1.8</target>
    </configuration>
</plugin>

开发插件类

@Mojo(name = "precommit", defaultPhase = LifecyclePhase.COMPILE)
public class PreCommitMojo extends AbstractMojo {
    @Parameter
    private String msg;
    @Parameter
    private List<String> options;
    @Parameter(property = "args")
    private String args;
    
    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        try {
            InputStream stream = this.getClass().getResourceAsStream("/pre-commit");
            byte[] buffer = new byte[stream.available()];
            stream.read(buffer);
            File file = new File("./.git/hooks/pre-commit");
            OutputStream outStream = new FileOutputStream(file);
            outStream.write(buffer);

            System.out.println("precommit:" + new String(buffer));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 插件类实现AbstractMojo抽象类,执行maven插件时,即执行execute()方法
  • 通过@Mojo指定目标名称为precommit,defaultPhase指定默认的执行周期
  • 通过@Parameter指定参数

deploy

mvn deploy -DaltDeploymentRepository=kkc::default::https://maven.abc.com/content/repositories/snapshots/

使用插件

<plugin>
    <groupId>com.taoche</groupId>
    <artifactId>taoche-pre-commit-tools</artifactId>
    <version>1.0-SNAPSHOT</version>
    <configuration>
        <msg>lalalalalalala</msg>
    </configuration>
    <executions>
      <execution>
        <id>pre-compile-check</id>
        <phase>compile</phase>
        <goals>
          <goal>precommit</goal>
        </goals>
      </execution>
    </executions>
</plugin>
  • 通过configuration指定maven插件参数
  • phase指定执行的周期
  • goal指定执行的目标
  • 在新的项目通过mvn install -Dargs=aaa 指定参数
  • maven-plugin-tools会自动生成plugin.xml,用于插件信息描述;如果标签不支持,尝试调整版本,再次导入,通常是版本缓存的问题