Tag Archives: mojo

教学贴:如何编写Maven2插件

Maven插件的编写非常容易,所以,简单的几个流水帐吧。

创建插件工程

# mvn archetype:generate

选择12,回答groupId,artifactId之类的问题,工程就OK了。导入到喜欢的IDE吧。

定义插件参数

完成的定义请参考Maven官方教程,这里简要介绍。

Maven2使用了很多注释中的Annotation来定义插件行为,完整文档点这里,常见的如:

Annotation

功能介绍
@goal <goalName>所谓目标了。每个Mojo类包含一个目标,一个Plugin可能若干Mojo类也就有若干目标了

@parameter expression="${aSystemProperty}" default-value="${anExpression}"

这是用于Mojo的属性的,可以通过表达式来获取系统参数,项目参数,以及从命令行输入参数。
@required同样用于Mojo的属性,定义该参数为必须的。
  

下面是简单的代码

package com.yuchengtech.emp;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;
import java.net.URL;
import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

/**
 * 用于编译EMP相关文件,生成部署资源
 *
 * @goal emp-compile
 *
 * @phase process-sources
 */
public class EmpCompileMojo extends AbstractMojo {
	/**
	 * 输出文件路径
	 *
	 * @parameter expression=
	 *            "${project.build.directory}/${project.build.finalName}/WEB-INF/tables"
	 * @required
	 */
	private File outputDirectory;

	/**
	 * EMP设计文件路径
	 *
	 * @parameter expression="${emp.design.dir}"
	 * @required
	 */
	private File empDesignDir;

	public void execute() throws MojoExecutionException {
		getLog().info("Design Files Folder: " + empDesignDir.getAbsolutePath());
		getLog().info(
				"Output Table Files Folder: "
						+ outputDirectory.getAbsolutePath());
		URL rule = this.getClass().getClassLoader().getResource(
				"rule-table.xml");
		Digester digester = DigesterLoader.createDigester(rule);

		Collection files = FileUtils.listFiles(empDesignDir,
				new String[] { "table" }, true);

		for (Iterator it = files.iterator(); it.hasNext();) {
			File table = (File) it.next();
			getLog().info("EMP: covert file - " + table.getName());
			ModelConverter convert = new ModelConverter(table, outputDirectory,
					digester);
			StringBuffer s = new StringBuffer();
			boolean result = convert.convert(s);
			if (!result) {
				throw new MojoExecutionException(s.toString());
			}
		}
	}
}

发布插件

使用简单的mvn install 之后就可以在本地使用这个插件了。或者发布到公共服务器上供更多人使用。

可以在项目中用命令行 mvn groupId:artifactId:goal来执行插件操作,也可以在项目POM中配置。

请继续参看Maven官方教程