构建maven项目插件_如何构建一个Maven插件
構建maven項目插件
使用Okta的身份管理平臺輕松部署您的應用程序 使用Okta的API在幾分鐘之內即可對任何應用程序中的用戶進行身份驗證,管理和保護。 今天嘗試Okta。
由于其插件生態系統的普及,Apache Maven仍然是Java領域最受歡迎的構建工具。 很容易找到現有的插件來執行您的應用程序所需的幾乎所有事情,從確保源文件具有許可證標頭到驗證版本之間的二進制兼容性。 有時,您需要編寫一個自定義插件來滿足產品中的要求。
在本教程中,我將向您展示如何構建一個簡單的Maven插件來解析項目的當前Git哈希,即git rev-parse --short HEAD 。
在開始之前,請確保安裝Java 8和Apache Maven 。 我使用SDKMAN來安裝它們。
如果您想觀看視頻, 我創建了此博客文章的截屏視頻 。
創建一個新的Maven項目
我將使用Maven構建新的Maven插件也就不足為奇了。 您可以使用自己喜歡的IDE來創建一個新項目,但是為了簡單起見,我將手動創建一個新的pom.xml文件(在名為example-maven-plugin的新目錄中:
<?xml version=&1.0& encoding=&UTF-8&?> <project xmlns=&http://maven.apache.org/POM/4.0.0&xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance&xsi:schemaLocation=&http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&><modelVersion>4.0.0</modelVersion><groupId>com.okta.example</groupId><artifactId>example-maven-plugin</artifactId><version>1.0-SNAPSHOT</version><packaging>maven-plugin</packaging><name>Example Maven Plugin</name><description>An Example Maven Plugin</description><properties><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding></properties>這是因為簡單,因為它得到,我已經定義了的Maven GAV(G roup ID,A rtifact ID,V版為),名稱,以及最重要的是我所設定的packaging到maven-plugin 。 雖然組ID幾乎可以是任何東西,但強烈建議使用反向域名表示法,類似于Java包 。
添加Maven依賴項
接下來,我需要定義一些對maven-core , maven-plugin-api和maven-plugin-annotations依賴。 這些都按照provided范圍限定,這意味著當插件運行時,使用的實際版本將取決于您安裝的Apache Maven的版本。
<dependencies><dependency><!-- plugin interfaces and base classes --><groupId>org.apache.maven</groupId><artifactId>maven-plugin-api</artifactId><version>3.6.0</version><scope>provided</scope></dependency><dependency><!-- needed when injecting the Maven Project into a plugin --><groupId>org.apache.maven</groupId><artifactId>maven-core</artifactId><version>3.6.0</version><scope>provided</scope></dependency><dependency><!-- annotations used to describe the plugin meta-data --><groupId>org.apache.maven.plugin-tools</groupId><artifactId>maven-plugin-annotations</artifactId><version>3.5</version><scope>provided</scope></dependency></dependencies>插件構建插件
插件是什么實際上給Maven的它的力量,其核心Maven是只是一個插件框架,所以很自然,我將使用Maven插件來構建一個Maven插件與Maven插件插件 。 烏龜一直向下!
實際上,自動定義了maven-plugin-plugin因為我使用了上面的maven-plugin的包裝類型,要使用較新的版本,我可以在pluginManagment部分中更新插件:
<pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-plugin-plugin</artifactId><version>3.6.0</version></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-site-plugin</artifactId><version>3.8.2</version></plugin></plugins></pluginManagement> </project>我還包括了Maven Site Plugin,它是可選的,在后面的文章中會有更多介紹。
這就對了! 如果您想一次復制并粘貼整個文件,可以從GitHub上獲取它。
編寫Maven插件代碼
在有趣的部分,編寫代碼! 一個Maven插件實際上是一個或多個“目標”的集合。 每個目標是由一個Java類中定義被稱為“魔”(M Aven的平原?LD 的J ava?bject)。
創建一個新類: src/main/java/com/okta/example/maven/GitVersionMojo.java
package com.okta.example.maven;import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject;/*** An example Maven Mojo that resolves the current project's git revision and adds * that a new {@code exampleVersion} property to the current Maven project.*/ @Mojo(name = "version", defaultPhase = LifecyclePhase.INITIALIZE) public class GitVersionMojo extends AbstractMojo {public void execute() throws MojoExecutionException, MojoFailureException {// The logic of our plugin will go here} }沒什么大不了的,現在我有了一個新的Maven插件,它有一個名為version目標。 該項目將在初始化項目時執行。 有幾個生命周期可供選擇,在本例中,我正在使用“初始化”,因為我希望我的插件在其他插件之前運行。 如果要創建一個插件來創建新文件,則可能需要使用“ generate-resources”階段。 請查看生命周期參考文檔 ,以獲取其他階段的描述。
此時,我可以使用mvn install構建項目,然后使用以下命令執行插件:
# mvn ${groupId}:${artifactId}:${goal} mvn com.okta.example:example-maven-plugin:version但是,由于execute方法為空,因此實際上還不會做任何事情。
添加Maven參數
為了使該插件實際起作用,我將添加幾個參數。 Maven參數在MOJO類中定義為字段:
/*** The git command used to retrieve the current commit hash.*/ @Parameter(property = "git.command", defaultValue = "git rev-parse --short HEAD") private String command;@Parameter(property = "project", readonly = true) private MavenProject project;值得注意的是,Javadoc對于Maven插件很重要,因為在生成特定于插件的文檔時將使用它。 由于我們都是優秀的開發人員,因此我們永遠不會忘記添加文檔,對嗎?
Parameter注釋告訴Maven向該字段中注入一個值。 這類似于Spring的Value注釋。 對于command字段,我將property值設置為git.command 。 這允許用戶使用標準-D表示法在命令行上更改值:
mvn com.okta.example:example-maven-plugin:version \-Dgit.command="git rev-parse --short=4 HEAD"注入MavenProject以便直接讀取或修改項目中的某些內容也是很常見的。 例如, MavenProject使您可以訪問依賴項以及pom.xml定義的任何內容。 就我而言,我將添加一個額外的屬性,該屬性可以在以后的構建中使用。
用Java執行命令
現在我們有了command參數,我們需要執行它! 定義一個新的getVersion方法來處理此邏輯:
public String getVersion(String command) throws MojoExecutionException {try {StringBuilder builder = new StringBuilder();Process process = Runtime.getRuntime().exec(command);Executors.newSingleThreadExecutor().submit(() ->new BufferedReader(new InputStreamReader(process.getInputStream())).lines().forEach(builder::append));int exitCode = process.waitFor();if (exitCode != 0) {throw new MojoExecutionException("Execution of command '" + command + "' failed with exit code: " + exitCode);}// return the outputreturn builder.toString();} catch (IOException | InterruptedException e) {throw new MojoExecutionException("Execution of command '" + command + "' failed", e);} }它使用Java的內置Runtime.exec()并捕獲輸出文本。 任何異常都將作為MojoExecutionException (這將導致生成失敗。)
接下來更新execute()方法:
public void execute() throws MojoExecutionException, MojoFailureException {// call the getVersion methodString version = getVersion(command);// define a new property in the Maven Projectproject.getProperties().put("exampleVersion", version);// Maven Plugins have built in logging toogetLog().info("Git hash: " + version); }就是這樣,現在我們只需要使用插件!
Maven插件的用法
到目前為止,我一直在使用以下命令直接執行插件:
mvn com.okta.example:example-maven-plugin:version通常,插件會添加到pom.xml因此它們會作為構建的一部分自動運行。 為了演示這一點,我將使用以下pom.xml (在另一個目錄中)創建一個新的Maven項目:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.okta.example</groupId><artifactId>example-usage</artifactId><version>1.0-SNAPSHOT</version><packaging>pom</packaging><build><plugins><plugin><groupId>com.okta.example</groupId><artifactId>example-maven-plugin</artifactId><version>1.0-SNAPSHOT</version><configuration><!-- optional, the command parameter can be changed here too --><command>git rev-parse --short=4 HEAD</command></configuration><executions><execution><goals><goal>version</goal></goals></execution></executions></plugin><plugin><groupId>com.github.ekryd.echo-maven-plugin</groupId><artifactId>echo-maven-plugin</artifactId><version>1.2.0</version><inherited>false</inherited><executions><execution><id>end</id><goals><goal>echo</goal></goals><phase>process-resources</phase><configuration><message>${line.separator}${line.separator}The project version is ${project.version}-${exampleVersion}${line.separator}</message></configuration></execution></executions></plugin></plugins></build> </project>在此項目結果上運行mvn package將給出輸出:
[INFO] Git hash: 1ab3行顯示了我的插件執行時,該插件定義的新exampleVersion屬性由echo-maven-plugin
注意:將插件添加到pom.xml ,可以使用簡寫表示法執行該插件: mvn <prefix>:<goal> ,通常,“ prefix”是工件ID減去“ -maven-plugin” 。 例如mvn example:version 。
Maven插件中的依賴注入
我們的插件很棒,而且很不錯,但是所有代碼都擠在一個文件中。 我喜歡將代碼分解為易于測試的塊。 輸入Sisu ,將在其上構建Maven容器。 Sisu是一個基于Guice的IoC容器,它是Spring的替代品。
這一切的真正含義是,我可以使用標準的JSR-330( @Inject )注釋來分解代碼,而不必擔心IoC容器的細節!
在src/main/java/com/okta/example/maven/VersionProvider.java創建一個新接口:
package com.okta.example.maven;import org.apache.maven.plugin.MojoExecutionException;public interface VersionProvider {String getVersion(String command) throws MojoExecutionException; }并將Runtime.exec邏輯從GitVersionMojo到新類src/main/java/com/okta/example/maven/RuntimeExecVersionProvider.java :
package com.okta.example.maven;import org.apache.maven.plugin.MojoExecutionException;import javax.inject.Named; import javax.inject.Singleton; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.concurrent.Executors;@Named @Singleton public class RuntimeExecVersionProvider implements VersionProvider {@Overridepublic String getVersion(String command) throws MojoExecutionException {try {StringBuilder builder = new StringBuilder();Process process = Runtime.getRuntime().exec(command);Executors.newSingleThreadExecutor().submit(() ->new BufferedReader(new InputStreamReader(process.getInputStream())).lines().forEach(builder::append));int exitCode = process.waitFor();if (exitCode != 0) {throw new MojoExecutionException("Execution of command '" + command + "' failed with exit code: " + exitCode);}// return the outputreturn builder.toString();} catch (IOException | InterruptedException e) {throw new MojoExecutionException("Execution of command '" + command + "' failed", e);}} }我添加了標準Java @Named和@Singleton批注,以將該類標記為由IoC容器管理的單例。 這等效于使用Spring的@Component 。
現在只需更新GitVersionMojo即可注入VersionProvider :
@Inject private VersionProvider versionProvider;public void execute() throws MojoExecutionException, MojoFailureException {String version = versionProvider.getVersion(command);project.getProperties().put("exampleVersion", version);getLog().info("Git hash: " + version); }這就對了! 您可以像以前一樣構建和運行插件,并獲得相同的結果。
一件事,文檔!
關于Maven,我最喜歡的事情之一是插件具有一致的文檔結構。 要生成文檔,請在pom.xml添加一個新的reporting部分:
<reporting><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-plugin-plugin</artifactId><reportSets><reportSet><reports><report>report</report></reports></reportSet></reportSets></plugin></plugins> </reporting>您還應該向項目添加更多元數據,但這是可選的。 例如,我將添加組織和前提條件,因為這些條件和前提條件已包含在生成的站點中:
<organization><name>Example, Inc</name><url>https://google.com/search?q=example.com</url> </organization> <prerequisites><maven>3.5.0</maven> </prerequisites>現在只需運行mvn site即可生成文檔! 在瀏覽器中打開target/site/plugin-info.html 。 明白為什么所有Javadoc都那么重要嗎?
了解更多
與往常一樣,您可以在GitHub上找到本教程的完整源代碼。 要了解有關構建插件的更多信息, Apache Maven項目提供了出色的文檔。 還可以查看以下其他教程:
- 使用Okta Maven插件在幾秒鐘內開始使用Okta
- Spring Boot登錄選項快速指南
- 使用Hamcrest使Java測試Groovy
- 許可Maven插件
- japicmp –一個用于二進制,源代碼和semver驗證的Maven插件
如果您喜歡本教程,請在Twitter @oktadev上關注我們。 我們還將每周在YouTube頻道上發布視頻教程。
使用Okta的身份管理平臺輕松部署您的應用程序 使用Okta的API在幾分鐘之內即可對任何應用程序中的用戶進行身份驗證,管理和保護。 今天嘗試Okta。
翻譯自: https://www.javacodegeeks.com/2019/11/how-to-build-maven-plugin.html
構建maven項目插件
總結
以上是生活随笔為你收集整理的构建maven项目插件_如何构建一个Maven插件的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 静态网站备案流程(静态网站备案)
- 下一篇: (simcity安卓版)
