Maven那些非常有用的 Plugin

左丘峰
2023-12-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,特别有用.

常用命令:

  • 准备发布: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>
复制代码

总结

如上只是一些本人总结的有用的插件,仅供参考.

 类似资料: