一夹抗、maven插件的開發(fā):
1绳慎、首先隨便創(chuàng)建一個maven工程。
2漠烧、然后在pom.xml文件中添加依賴:
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.5</version>
<scope>provided</scope>
</dependency>
這時還要添加一下打包方式:
<packaging>maven-plugin</packaging>
然后就可以隨便創(chuàng)建一個類來繼承AbstractMojo
類并重寫execute()
方法就可以了杏愤。
@Mojo( name = "exportDataToFile")
public class WriteDataToFile extends AbstractMojo {
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
...//要執(zhí)行的代碼
}
}
基本一個最簡單的插件就寫完了。
執(zhí)行install
命令就可以將程序打成jar包并放入你所綁定的maven庫了已脓。
二珊楼、Maven插件的調(diào)試
以IntelliJ IDEA為例,通常我們調(diào)試項目時度液,都是直接點擊 debug
調(diào)試按鈕即可厕宗。但maven編寫的插件就不同了,由于插件需要打包成Jar加載到項目中堕担,所以如果我們需要在編寫插件源碼時調(diào)試的話已慢,就不能直接點擊調(diào)試按鈕了(因為沒有Main類),那么該怎么辦呢照宝?
這里提供一種簡單解決辦法:
假設(shè)及正在編寫的maven插件A
擁有如下坐標(biāo):
<groupId>com.xx</groupId>
<artifactId>exportDataToFile</artifactId>
<version>1.0.0</version>
再假設(shè)你想將這個插件A
用在某個項目B
中蛇受,而項目B
中的pom.xml
是這樣定義這個插件的:
<plugin>
<groupId>com.xx</groupId>
<artifactId>exportDataToFile</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<id>exportDataToFile</id>
<phase>compile</phase>
<goals>
<goal>exportDataToFile</goal>
</goals>
</execution>
</executions>
</plugin>
其中,exportDataToFile
即為你要調(diào)試的目標(biāo)的名字厕鹃。
那么可以在Terminal中輸入一下命令啟動監(jiān)聽端口:
mvnDebug com.xx:exportDataToFile:1.0.0:exportDataToFile
可能到這時還是不知道這么做有什么用兢仰,好像和我們想做的事沒什么關(guān)系乍丈,這里做完以上步驟后項目B
就不用再管了,這時我們要到之前開發(fā)插件A
的源代碼中去打斷點把将,什么意思轻专?就是和正常項目一樣在A中你要測試的地方打上斷點。
選中插件本身在鼠標(biāo)右鍵debug運(yùn)行就可以進(jìn)入斷點模式了察蹲,如下圖:
如果發(fā)現(xiàn)自己這里沒有自己要的插件的選項(這就尷尬了)请垛,那就在該項目pom.xml
文件中引入本身(你引入的不是項目本身,而是編譯打包后的jar包)洽议,實在不行就照著一下代碼寫就行了(可以百度一下各參數(shù)的含義):
<build>
<finalName>xx</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>com.xx</groupId>
<artifactId>exportDataToFile</artifactId>
<version>1.0.0</version>
<configuration>
<outDir>xxx.xxx.xxx</outDir>
<configFile>xxx.xxx.xxx</configFile>
</configuration>
</plugin>
</plugins>
</build>
最后調(diào)完不要忘記關(guān)閉B
項目的監(jiān)聽端口宗收,快捷鍵Ctrl+C
行了。