一直在使用Maven,用了各种各样的插件,但是有时候没有的话,还是需要自己写点。写一个插件并不难,会写插件的另一个好处就是了解了更多的Maven工作机制的内幕。对更好的使用Maven有帮助。
首先创建一个Maven项目,名叫plugin-example1。
这里要理解一个术语:mojo,就是Maven Plain Old Java Object,也就是一个普通的Java类。
我们需要mojo的api库,所以在pom.xml中添加一个依赖:
<dependencies> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <version>2.0</version> </dependency> </dependencies>创建一个Example类,继承于AbstractMojo,实现execute方法。
public class Example extends AbstractMojo{ public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("Hello world"); } }getLog()获取的是AbstractMojo内部的log,类型是:org.apache.maven.plugin.logging.Log;
现在修改一下工程的描述信息:
<groupId>org.freebird</groupId> <artifactId>plugin-example1</artifactId> <version>1.0-SNAPSHOT</version> <packaging>maven-plugin</packaging> <name>plugin-example1</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>
现在编译吧,很快就遇到错误:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-plugin-plugin:2.9:descriptor (default-descriptor) on project plugin-example1: Error extracting plugin descriptor: 'No mojo definitions were found for plugin: org.freebird:plugin-example1.' -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-plugin-plugin:2.9:descriptor (default-descriptor) on project plugin-example1: Error extracting plugin descriptor: 'No mojo definitions were found for plugin: org.freebird:plugin-example1.'
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-plugin-plugin</artifactId> <version>3.0</version> <executions> </executions> <configuration> <!-- Needed for Java 5 annotation based configuration, for some reason. --> <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound> </configuration> </plugin> </plugins> </build>
这样编译就通过了。或者在类的注视上添加一个descriptor:
/** * * @goal sayhi */ public class Example extends AbstractMojo{
为了将Maven部署在私服上,需要加上如下配置:
<distributionManagement> <snapshotRepository> <id>snapshots</id> <url>http://your_server:8080/nexus/content/repositories/snapshots</url> </snapshotRepository> </distributionManagement>
部署成功。