自定义maven插件开发

自定义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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值