自定义Maven2插件

一、创建一个插件项目
> mvn archetype:create -DgroupId=org.sonatype.mavenbook.plugins -DartifactId=first-maven-plugin -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-mojo

maven会自动到远程库去下载maven-archetype-mojo的插件;
创建成功会生成一个first-maven-plugin的文件夹,里有一个pom.xml文件,内容:

org.sonatype.mavenbook.plugins  
first-maven-plugin  
maven-plugin  
1.0-SNAPSHOT  
first-maven-plugin Maven Mojo  
http://maven.apache.org  
  
  
      
        org.apache.maven  
        maven-plugin-api  
        2.0  
      
      
        junit  
        junit  
        3.8.1  
        test  
      
  

二、创建一个MOJO
MOJO就是一个供插件调用处理的普通类。

package org.sonatype.mavenbook.plugins;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

/**
* Echos an object string to the output screen.
* 
* @goal echo
*/
public class EchoMojo extends AbstractMojo {
  /**
    * Any Object to print out.
    * 
    * @parameter expression="${echo.message}"
    *                        default-value="Hello Maven World..."
    */
  private Object message;

  public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info(message.toString());
  }
}

创建了一个EchoMojo类,必须继承AbstractMojo类,实现execute方法,这个方法就是插件调用的入口;

三、build, run自定义插件
> mvn clean install
插件运行遵循groupId:artifactId:version:goal格式;

> mvn org.sonatype.mavenbook.plugins:first-maven-plugin:1.0-SNAPSHOT:echo -Decho.message="The Eagle has Landed" 
D:\code\first-maven-plugin>mvn org.sonatype.mavenbook.plugins:first-maven-plugin:1.0-SNAPSHOT:echo -Decho.message="The Eagle has Landed"
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building first-maven-plugin Maven Mojo
[INFO]        task-segment: [org.sonatype.mavenbook.plugins:first-maven-plugin:1.0-SNAPSHOT:echo]
[INFO] ------------------------------------------------------------------------
[INFO] [first:echo {execution: default-cli}]
[INFO] The Eagle has Landed
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Sat Jul 31 14:26:50 CST 2010
[INFO] Final Memory: 1M/4M
[INFO] ------------------------------------------------------------------------

上面命令中,出来一个echo,这个就是goal,在EchoMojo类里用注释定义@goal echo; 可能上面的命令太长,怎样做到像archetype:create一样写法?可以定义前缀;

四、定义前缀
在setting.xml文件加:

  
  org.sonatype.mavenbook.plugins  
  

然后:
> mvn first:echo -Decho.message="My first Maven plugin"
非常简单。
如果插件的artifactId遵循maven-first-plugin,或者first-maven-plugin模式。Maven就会自动为你的插件赋予前缀first。
${prefix}-maven-plugin, OR maven-${prefix}-plugin
也可自定义前缀,在pom.xml加:

  
    
      
      first-maven-plugin  
      2.3  
        
        first  
        
      
    
  
如有帮助, 可以支持一下
分享到:

发表评论

昵称

沙发空缺中,还不快抢~