2012-07-02 18:19
310人阅读
评论(3)
收藏
举报
创建一个Example类,继承于AbstractMojo,实现execute方法。
代码很简单:
getLog()获取的是AbstractMojo内部的log,类型是:org.apache.maven.plugin.logging.Log;
至少在Mojo的开发中,不要使用其他的Log基础设施。
注意,packaging的值是maven-plugin
需要加入一个maven-plugin-plugin来生成descriptor。不知道Maven的官方文档中为什么不提。
然后运行mvn clean package deploy
一直在使用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>
代码很简单:
- public class Example extends AbstractMojo{
- public void execute() throws MojoExecutionException, MojoFailureException {
- getLog().info("Hello world");
- }
- }
至少在Mojo的开发中,不要使用其他的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>
注意,packaging的值是maven-plugin
现在编译吧,很快就遇到错误:
- [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.'
需要加入一个maven-plugin-plugin来生成descriptor。不知道Maven的官方文档中为什么不提。
- <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>
然后运行mvn clean package deploy
部署成功。