Maven插件的编写

来源:互联网 发布:知乎 闲书 编辑:程序博客网 时间:2024/05/16 01:01

Eclipse上如果想要开发Maven的插件,首先要确保该eclipse已经安装了m2e插件。IDEA则自带了Maven的插件,可以直接进行开发。

Eclipse

  1. 新建一个Maven工程

create new

2 选择由archetype生成(注意,不要勾选)

generate from archetype

3 选择archetype

在filter选项中输入plugin进行过滤,选择筛选出来的第一个archetype:maven-archetype-plugin。

select archetype

4 填写坐标信息

fill in coordination

5 查看自动生成的代码

自动生成的Mojo类:MyMojo

package dev.lyj.summary.mymojo_maven_plugin;import org.apache.maven.plugin.AbstractMojo;import org.apache.maven.plugin.MojoExecutionException;import org.apache.maven.plugins.annotations.LifecyclePhase;import org.apache.maven.plugins.annotations.Mojo;import org.apache.maven.plugins.annotations.Parameter;import org.apache.maven.plugins.annotations.ResolutionScope;import java.io.File;import java.io.FileWriter;import java.io.IOException;/** * Goal which touches a timestamp file. * * @deprecated Don't use! */@Mojo( name = "touch", defaultPhase = LifecyclePhase.PROCESS_SOURCES )public class MyMojo extends AbstractMojo{    /**     * Location of the file.     */    @Parameter( defaultValue = "${project.build.directory}", property = "outputDir", required = true )    private File outputDirectory;    public void execute() throws MojoExecutionException    {        File f = outputDirectory;        if ( !f.exists() )        {            f.mkdirs();        }        File touch = new File( f, "touch.txt" );        FileWriter w = null;        try        {            w = new FileWriter( touch );            w.write( "touch.txt" );        }        catch ( IOException e )        {            throw new MojoExecutionException( "Error creating file " + touch, e );        }        finally        {            if ( w != null )            {                try                {                    w.close();                }                catch ( IOException e )                {                    // ignore                }            }        }    }}

自动生成的pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>dev.lyj.summary</groupId>  <artifactId>mymojo-maven-plugin</artifactId>  <version>0.0.1-SNAPSHOT</version>  <packaging>maven-plugin</packaging>  <name>mymojo-maven-plugin Maven Plugin</name>  <!-- FIXME change it to the project's website -->  <url>http://maven.apache.org</url>  <properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  </properties>  <dependencies>    <dependency>      <groupId>org.apache.maven</groupId>      <artifactId>maven-plugin-api</artifactId>      <version>2.0</version>    </dependency>    <dependency>      <groupId>org.apache.maven.plugin-tools</groupId>      <artifactId>maven-plugin-annotations</artifactId>      <version>3.2</version>      <scope>provided</scope>    </dependency>    <dependency>      <groupId>org.codehaus.plexus</groupId>      <artifactId>plexus-utils</artifactId>      <version>3.0.8</version>    </dependency>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.8.2</version>      <scope>test</scope>    </dependency>  </dependencies>  <build>    <plugins>      <plugin>        <groupId>org.apache.maven.plugins</groupId>        <artifactId>maven-plugin-plugin</artifactId>        <version>3.2</version>        <configuration>          <goalPrefix>mymojo-maven-plugin</goalPrefix>          <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>        </configuration>        <executions>          <execution>            <id>mojo-descriptor</id>            <goals>              <goal>descriptor</goal>            </goals>          </execution>          <execution>            <id>help-goal</id>            <goals>              <goal>helpmojo</goal>            </goals>          </execution>        </executions>      </plugin>    </plugins>  </build>  <profiles>    <profile>      <id>run-its</id>      <build>        <plugins>          <plugin>            <groupId>org.apache.maven.plugins</groupId>            <artifactId>maven-invoker-plugin</artifactId>            <version>1.7</version>            <configuration>              <debug>true</debug>              <cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>              <pomIncludes>                <pomInclude>*/pom.xml</pomInclude>              </pomIncludes>              <postBuildHookScript>verify</postBuildHookScript>              <localRepositoryPath>${project.build.directory}/local-repo</localRepositoryPath>              <settingsFile>src/it/settings.xml</settingsFile>              <goals>                <goal>clean</goal>                <goal>test-compile</goal>              </goals>            </configuration>            <executions>              <execution>                <id>integration-test</id>                <goals>                  <goal>install</goal>                  <goal>integration-test</goal>                  <goal>verify</goal>                </goals>              </execution>            </executions>          </plugin>        </plugins>      </build>    </profile>  </profiles></project>

IDEA

IDEA与Eclipse生成的稍微有点不同:
首先,在选择archetype上,idea给的选项中没有:maven-archetype-plugin,而是:maven-archetype-mojo。

idea  select archetype

idea自动生成的类MyMyjo。

package dev.lyj.summary;import org.apache.maven.plugin.AbstractMojo;import org.apache.maven.plugin.MojoExecutionException;import java.io.File;import java.io.FileWriter;import java.io.IOException;/** * 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    {        File f = outputDirectory;        if ( !f.exists() )        {            f.mkdirs();        }        File touch = new File( f, "touch.txt" );        FileWriter w = null;        try        {            w = new FileWriter( touch );            w.write( "touch.txt" );        }        catch ( IOException e )        {            throw new MojoExecutionException( "Error creating file " + touch, e );        }        finally        {            if ( w != null )            {                try                {                    w.close();                }                catch ( IOException e )                {                    // ignore                }            }        }    }}

可以看出,这两种archetype生成的类,还是有差别的。第一种生成的Mojo类上使用的是普通注解 @Mojo,而第二种生成的Mojo类上使用的是Javadoc式的注解@goal和@phase,总之是两种风格的注解。
eclipse mojo

idea mojo

通过对比发现,第一种的注解没有第二种的简单明了,第二种一看就知道goal是touch,默认phase是process-sources,而且第一种注解上边有个注释标注这种写法(@deprecated)过时了。另外在参数配置上也有不同。

maven-archetype-plugin:

parameter

maven-archetype-mojo:

idea parameter

所以,我还是倾向于适用idea中插件生成的这种写法。

不过,我看了一下,官方给的例子,用的还是第一种的写法。

maven official

接下来我们来看一下很重的一部分,参数的配置方法。

Mojo离开了参数一点儿意义都没有。参数提供了一些重要功能:

  1. 它提供了钩子机制,允许用户根据需求调整插件的行为
  2. 它提供了一种轻松获取POM中元素值的方式,而不用操纵对象

在Mojo中定义参数

在mojo中定义参数就像和创建实例变量一样简单,然后为他们添加注解。下边就是一个简单的mojo参数的例子:

    /**     * The greeting to display.     */    @Parameter( property = "sayhi.greeting", defaultValue = "Hello World!" )    private String greeting;

注解的上边是参数的描述部分。这个参数注解标识了这个变量是一个mojo参数。

  1. 注解中的defaultValue参数,定义了标注变量的默认值。它的值可以包含执行project的表达式,例如 “${project.version}”(更多内容请看“Parameter Expressions” 文档)。
  2. property参数表示,允许通过获取命令行中-D选项指定的系统属性,来配置mojo参数。

在项目中使用Mojo参数

参数定义完了,该怎么使用呢?
插件参数值的设置,将作为插件定义的一部分,配置在Maven项目中的pom.xml文件中。一个配置插件的例子:

<plugin>  <groupId>sample.plugin</groupId>  <artifactId>hello-maven-plugin</artifactId>  <version>1.0-SNAPSHOT</version>  <configuration>    <greeting>Welcome</greeting>  </configuration></plugin>

在配置区域,参数的名字(mojo类的属性名)”greeting”作为元素名称,元素内容”Welcome”则被作为值赋给参数。
更多详细内容参见 Guide to Configuring Plugins

单值的参数类型
下边列出的是可以在你的mojo中使用的各种单值,以及这些单值在POM中的使用规则。

Boolean 布尔

Fixed-Point Numbers 整型

Floating-Point Numbers 浮点型

Dates 日期

Files and Directories 文件和目录

URLs 网络地址

Plain Text 普通文本

Enums 枚举类型

值参数类型

Arrays 数组

Collections 集合

Maps map

Properties 属性

Other Object Classes 其他对象类类型

0 0