開發自己的Maven外掛之一:hello world
阿新 • • 發佈:2018-12-18
一直在使用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;至少在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部署成功。