自定义maven插件开发
需求背景:希望能有工具抽取当前项目中所有的接口信息进行接口管理
实现方式:自定义maven插件,在maven打包编译项目时实现对项目内的接口进行扫描并记录
下面以实际操作步骤举例讲解:
1.创建maven项目
2.生成项目后,pom.xml可以看到package类型为
<packaging>maven-plugin</packaging>
3.插件的两种实现方式
src下面有一个MyMojo的class类,生成了一个很简单demo样例。但是生成的样例比较简单是基于JavaDoc的,因为Mojo的配置有两种方式,一种是JavaDoc + Tag,即连接示例代码所使用的方式。另一种是注解,使用@Mojo, @Parameter等annotation来配置。
1)javaDoc形式:
/**
* Goal which touches a timestamp file.
*
* @goal touch
*
* @phase process-sources
*/
public class MyMojo extends AbstractMojo {
/**
* Location of the file.
* @parameter expression="${project.build.directory}"
* @required
*/
private File outputDirectory;
public void execute() throws MojoExecutionException {
// 自定义业务实现
}
}
2)注解形式:
@Mojo( name = "first", defaultPhase = LifecyclePhase.COMPILE)
public class MyFirstPlugin extends AbstractMojo {
@Parameter( defaultValue = "${project.build.directory}", property = "outputDir", required = true )
private File outputDirectory;
@Parameter(property = "basePackage", required = true)
private String basePackage;
public void execute() throws MojoExecutionException, MojoFailureException {
// 自定义业务实现
}
}
使用注解形式的时候pom需要添加依赖
<!-- dependencies to annotations -->
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.4</version>
<scope>provided</scope>
</dependency>
两种形式都需要添加plugin依赖
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<version>3.5</version>
</plugin>
</plugins>
</build>
4. 业务代码实现
无论是javaDoc还是注解的形式,都需要继承AbstractMojo类实现execute方法,引入编写的插件在项目打包时会运行execute方法体,在其中自定义业务代码。
5.调用插件:
创建一个新的项目,在pom中引入之前编写的插件(下面演示的是引入first插件,仅在当前项目compile时运行,并且配置了一个参数值basePackage)
<build>
<plugins>
<plugin>
<groupId>org.example</groupId>
<artifactId>MojoDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<configuration>
<basePackage>com.example.demo</basePackage>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>first</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>