开发自己的Maven插件之一:hello world

来源:互联网 发布:linux 内核编译 编辑:程序博客网 时间:2024/05/20 06:08
310人阅读评论(3)收藏举报

一直在使用Maven,用了各种各样的插件,但是有时候没有的话,还是需要自己写点。写一个插件并不难,会写插件的另一个好处就是了解了更多的Maven工作机制的内幕。对更好的使用Maven有帮助。

首先创建一个Maven项目,名叫plugin-example1。

这里要理解一个术语:mojo,就是Maven Plain Old Java Object,也就是一个普通的Java类。
我们需要mojo的api库,所以在pom.xml中添加一个依赖:

[html] view plaincopyprint?
  1. <dependencies>
  2. <dependency>
  3. <groupId>org.apache.maven</groupId>
  4. <artifactId>maven-plugin-api</artifactId>
  5. <version>2.0</version>
  6. </dependency>
  7. </dependencies>
创建一个Example类,继承于AbstractMojo,实现execute方法。
代码很简单:
[java] view plaincopyprint?
  1. public class Exampleextends AbstractMojo{
  2. public void execute()throws MojoExecutionException, MojoFailureException {
  3. getLog().info("Hello world");
  4. }
  5. }
getLog()获取的是AbstractMojo内部的log,类型是:org.apache.maven.plugin.logging.Log;
至少在Mojo的开发中,不要使用其他的Log基础设施。


现在修改一下工程的描述信息:

[html] view plaincopyprint?
  1. <groupId>org.freebird</groupId>
  2. <artifactId>plugin-example1</artifactId>
  3. <version>1.0-SNAPSHOT</version>
  4. <packaging>maven-plugin</packaging>
  5. <name>plugin-example1</name>
  6. <url>http://maven.apache.org</url>
  7. <properties>
  8. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  9. </properties>

注意,packaging的值是maven-plugin

现在编译吧,很快就遇到错误:

[plain] view plaincopyprint?
  1. [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]
  2. 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的官方文档中为什么不提。

[html] view plaincopyprint?
  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.apache.maven.plugins</groupId>
  5. <artifactId>maven-plugin-plugin</artifactId>
  6. <version>3.0</version>
  7. <executions>
  8. </executions>
  9. <configuration>
  10. <!-- Needed for Java 5 annotation based configuration, for some reason. -->
  11. <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
  12. </configuration>
  13. </plugin>
  14. </plugins>
  15. </build>

这样编译就通过了。或者在类的注视上添加一个descriptor:

[java] view plaincopyprint?
  1. /**
  2. *
  3. * @goal sayhi
  4. */
  5. public class Exampleextends AbstractMojo{

 

为了将Maven部署在私服上,需要加上如下配置:

[html] view plaincopyprint?
  1. <distributionManagement>
  2. <snapshotRepository>
  3. <id>snapshots</id>
  4. <url>http://your_server:8080/nexus/content/repositories/snapshots</url>
  5. </snapshotRepository>
  6. </distributionManagement>

然后运行mvn clean package deploy

部署成功。

原创粉丝点击