Maven那些非常有用的 Plugin

candyleer發表於2019-03-01

背景

maven 作為Java 開發者必備的專案管理和構建工具,已經深深的影響了一代 Javaer.? 本文主要記錄一些你可能用過但是不那麼常用,但是關鍵時刻可能又非常有用的plugin.以備需要的時候檢視.只列舉外掛的一些常用配置;

編譯

maven-compiler-plugin

用於便於 Java 專案mvn compile就是使用它.不多說.

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <source>${java.version}</source>
        <target>${java.version}</target>
        <encoding>UTF-8</encoding>
    </configuration>
</plugin>
複製程式碼

maven-source-plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-source-plugin</artifactId>
    <version>3.0.1</version>
    <executions>
        <execution>
            <id>attach-sources</id>
            <phase>none</phase>
            <goals>
                <goal>jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>
複製程式碼

可執行 Jar 包和重新命名Package

maven-shade-plugin

maven-shade-plugin主要提供了 rename 包名,將依賴包放進一個 jar 中,簡直是一個萬能的外掛,使用,根據實際經驗,這個外掛在提供防止和其他包有衝突的 sdk 的時候特別有用.

  • filters: 只選擇 jar 包中需要的包名或者 exclude 不需要的包名
  • artifactSet :選擇哪些 jar 包放入最終的 jar 包中
  • relocations:重新命名包名路徑,也可以選擇 includes 和 excludes
  • Transformers :合併器的選擇,就是公共的資原始檔應該如何合併.
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.0.0</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <shadedArtifactAttached>false</shadedArtifactAttached> <createDependencyReducedPom>true</createDependencyReducedPom>
                <createSourcesJar>true</createSourcesJar>
                <shadeSourcesContent>true</shadeSourcesContent>
                <filters>
                    <filter>
                        <artifact>io.jaegertracing:jaeger-thrift</artifact>
                        <includes>
                            <include>jaeger/org/apache/**</include>
                            <include>io/jaegertracing/**</include>
                        </includes>
                    </filter>
                    <filter>
                        <artifact>ch.qos.logback:logback-classic</artifact>
                        <excludes>
                            <exclude>META-INF/services/**</exclude>
                        </excludes>
                    </filter>
                </filters>
                <artifactSet>
                    <excludes>
                        <exclude>net.bytebuddy:byte-buddy:jar:</exclude>
                    </excludes>
                </artifactSet>
                <relocations>
                    <relocation>
                        <pattern>com.squareup</pattern>
                        <shadedPattern>${shade.package}.com.squareup</shadedPattern>
                    </relocation>
                </relocations>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <manifestEntries>
                            <Premain-Class>${premain.class}</Premain-Class>
                        </manifestEntries>
                    </transformer>
                </transformers>
            </configuration>
        </execution>
    </executions>
</plugin>
複製程式碼

maven-jar-plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>com.test.fastjar.fatjartest.FatJarTestApplication</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>
複製程式碼

maven-assembly-plugin

此外掛主要在打包上線過程中使用,但是也可以用來構建可執行的 jar 包.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        <archive>
            <manifest>
                <mainClass>com.test.fastjar.fatjartest.FatJarTestApplication</mainClass>
            </manifest>
        </archive>
    </configuration>
    <executions>
        <execution>
            <id>assemble-all</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>
複製程式碼

釋出

maven-release-plugin

規範化 專案的構建釋出,自動修改POM版本,自動打 tag,特別有用.

Maven那些非常有用的 Plugin
常用命令:

  • 準備釋出:mvn release:prepare
  • 執行釋出:mvn release:perform -Darguments="-Dmaven.deploy.skip=true"(如果不想推送 jar 包到倉庫中)
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-release-plugin</artifactId>
    <version>2.5.3</version>
    <configuration>
        <tagNameFormat>@{project.version}</tagNameFormat>
        <autoVersionSubmodules>true</autoVersionSubmodules>
    </configuration>
</plugin>
複製程式碼

打包

主要目的是將所需要的資源都壓縮成一個 tar或者zip包,便於上線釋出.

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-assembly-plugin</artifactId>
	<version>3.0.0</version>
	<configuration>
		<appendAssemblyId>false</appendAssemblyId>
		<filters>
            <filter>src/assembly/filter.properties</filter>
          </filters>
		<descriptors>
			<descriptor>src/assembly/assembly.xml</descriptor>
		</descriptors>
	</configuration>
	<executions>
		<execution>
			<id>make-assembly</id> <!-- this is used for inheritance merges -->
			<phase>package</phase> <!-- bind to the packaging phase -->
			<goals>
				<goal>single</goal>
			</goals>
		</execution>
	</executions>
</plugin>
複製程式碼

重點在於src/assembly/assembly.xml如何配置,如下是將一個單獨的 jar 包打包上線.

  • assembly 過程中也可以 filter 資原始檔.
<assembly
        xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
    <id>bin</id>
    <formats>
        <format>tar.gz</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <fileSets>
        <fileSet>
            <directory>src/bin/${profileActive}</directory>
            <outputDirectory>${project.artifactId}/bin</outputDirectory>
            <fileMode>0755</fileMode>
        </fileSet>
    </fileSets>
    <files>
        <file>
            <source>target/${project.artifactId}-${project.version}.jar</source>
            <outputDirectory>${project.artifactId}/</outputDirectory>
        </file>
    </files>
</assembly>
複製程式碼

命令執行

maven-antrun-plugin

執行 ant 命令

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.8</version>
    <executions>
        <execution>
            <id>unpack</id>
            <phase>package</phase>
            <configuration>
                <target>
                    <echo message="unjar" />
                    <unzip src="${project.build.directory}/${artifactId}-${version}.jar" dest="${project.build.directory}/unpacked/" />
                </target>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
        <execution>
            <id>copy</id>
            <phase>package</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <target>
                    <copy file="${project.build.directory}/${project.artifactId}-${project.version}.jar" tofile="../agent.jar" overwrite="true" />
                    <copy file="${project.build.directory}/classes/version" tofile="../version" overwrite="true" />
                </target>
            </configuration>
        </execution>
    </executions>
</plugin>
複製程式碼

程式碼生成

mybatis-generator-plugin

<plugin>
	<groupId>org.mybatis.generator</groupId>
	<artifactId>mybatis-generator-maven-plugin</artifactId>
	<version>1.3.7</version>
	<dependencies>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.41</version>
		</dependency>
		<dependency>
			<groupId>com.itfsw</groupId>
			<artifactId>mybatis-generator-plugin</artifactId>
			<version>1.2.15</version>
		</dependency>
	</dependencies>
	<configuration>
		<configurationFile>generatorConfig.xml</configurationFile>
		<overwrite>true</overwrite>
		<verbose>true</verbose>
	</configuration>
</plugin>
複製程式碼

generatorConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
       "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
   <context id="symphony">

       <property name="autoDelimitKeywords" value="true"/>
       <property name="beginningDelimiter" value="`"/>
       <property name="endingDelimiter" value="`"/>

       <plugin type="com.itfsw.mybatis.generator.plugins.SelectOneByExamplePlugin"/>
       <plugin type="com.itfsw.mybatis.generator.plugins.LimitPlugin"/>
       <plugin type="com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin"/>
       <plugin type="com.itfsw.mybatis.generator.plugins.ExampleEnhancedPlugin"/>
       <plugin type="com.itfsw.mybatis.generator.plugins.BatchInsertPlugin"/>
       <plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
       <plugin type="com.itfsw.mybatis.generator.plugins.SelectSelectivePlugin"/>
       <commentGenerator>
           <property name="suppressAllComments" value="false"/>
           <property name="suppressDate" value="true"/>
       </commentGenerator>
       <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.8.1:5711/xxx?useSSL=false"
                       userId="xxx" password="xxx"/>
       <javaModelGenerator targetPackage="com.xxx.model"
                           targetProject="src/main/java"/>
       <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources" />
       <javaClientGenerator targetPackage="com.xxx.dao"
                            targetProject="src/main/java" type="XMLMAPPER"/>
       <!--支援返回主鍵-->
       <table tableName="app_deploy">
           <generatedKey column="id" sqlStatement="JDBC" identity="true"/>
       </table>
   </context>
</generatorConfiguration>
複製程式碼

protobuf-maven-plugin

用於根據.proto 檔案生成 protobuf 檔案

 <extensions>
   <extension>
       <groupId>kr.motd.maven</groupId>
       <artifactId>os-maven-plugin</artifactId>
       <version>1.5.0.Final</version>
   </extension>
 </extensions>
 <plugin>
   <groupId>org.xolstice.maven.plugins</groupId>
   <artifactId>protobuf-maven-plugin</artifactId>
   <executions>
     <execution>
       <id>Generate Java from protocol buffers</id>
       <phase>generate-sources</phase>
       <goals>
         <goal>compile</goal>
         <goal>compile-custom</goal>
       </goals>
       <configuration>
         <checkStaleness>true</checkStaleness>
         <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.18.0:exe:${os.detected.classifier}</pluginArtifact>
         <pluginId>grpc-java</pluginId>
         <protoSourceRoot>${project.build.directory}/generated-sources/_proto</protoSourceRoot>
         <protocArtifact>com.google.protobuf:protoc:3.6.1:exe:${os.detected.classifier}</protocArtifact>
       </configuration>
     </execution>
   </executions>
 </plugin>
複製程式碼

SCM

maven-scm-plugin

從遠端倉庫獲取原始碼,用於專案.

<plugin>
<artifactId>maven-scm-plugin</artifactId>
<executions>
  <execution>
    <id>Checkout Helm Protocol Buffers source code</id>
    <phase>generate-sources</phase>
    <goals>
      <goal>checkout</goal>
    </goals>
    <configuration>
      <checkoutDirectory>${project.build.directory}/generated-sources/helm</checkoutDirectory>
      <connectionUrl>scm:git:https://github.com/kubernetes/helm.git</connectionUrl>
      <includes>_proto/hapi/**</includes>
      <scmVersion>v2.12.3</scmVersion>
      <scmVersionType>tag</scmVersionType>
    </configuration>
  </execution>
</executions>
</plugin>
複製程式碼

總結

如上只是一些本人總結的有用的外掛,僅供參考.

相關文章