• maven项目如何打包运行指定java程序(maven-shade-plugin插件的使用)


    其实maven项目的打包就是将项目代码打包成可执行文件,在maven中有默认的打包插件,但是想要运行指定java程序就要使用maven-shade-plugin插件

    maven-jar-plugin是maven的默认打包插件,用来创建 project jar

    maven-shade-plugin用来打可执行包,包含依赖,以及对依赖进行取舍过滤

    官方网站:https://maven.apache.org/plugins/maven-shade-plugin/index.html

    1 maven-shade-plugin介绍

    maven-plugin-shade 插件提供了两个主要的能力:

    1. 把整个项目(包含它的依赖)都打包到一个 “uber-jar” 中;
    2. shade - 即重命名某些依赖的包。

    具体来说,它提供了以下功能:

    1. 按需选择要添加到最终 jar 包中依赖;
    2. 重定位 class 文件;
    3. 生成可执行 jar 包;
    4. 生成项目资源文件。

    2 基本用法

    maven-plugin-shade 必须和 Maven 构建生命周期中的 package 阶段绑定,
    也就是说,当执行mvn package时会自动触发 shade
    要使用 maven-plugin-shade,只需要在 pom.xml 的 < plugins > 标签下添加它的配置即可,示例如下:

    <project>
        ...
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.pluginsgroupId>
                    <artifactId>maven-shade-pluginartifactId>
                    <version>3.2.4version>
                    <executions>
                        <execution>
                            
                            <phase>packagephase>
                            <goals>
                                <goal>shadegoal>
                            goals>
                        execution>
                    executions>
                    <configuration>
                        
                    configuration>
                plugin>
            plugins>
        build>
        ...
    project>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    项目中常用写法

    
    <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">
    
    
    
    <build>  
        <plugins>  
            <plugin>  
                <groupId>org.apache.maven.pluginsgroupId>  
                <artifactId>maven-shade-pluginartifactId>  
                
                <version>1.4version>  
                <executions>  
                    <execution>  
                        <phase>packagephase>  
                        <goals>  
                            <goal>shadegoal>  
                        goals>  
                        <configuration>  
                            
                            <filters>  
                                <filter>  
                                    <artifact>*:*artifact>  
                                    <excludes>  
                                        <exclude>META-INF/*.SFexclude>  
                                        <exclude>META-INF/*.DSAexclude>  
                                        <exclude>META-INF/*.RSAexclude>  
                                    excludes>  
                                filter>  
                            filters>  
                            <transformers>  
                                
                                <transformer  
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">  
                                    <mainClass>cn.fileserver.HttpFileServermainClass>  
                                transformer>  
                                
                                <transformer  
                                    implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">  
                                    <resource>META-INF/spring.handlersresource>  
                                transformer>  
                                <transformer  
                                    implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">  
                                    <resource>META-INF/spring.schemasresource>  
                                transformer>  
                            transformers>  
                        configuration>  
                    execution>  
                executions>  
            plugin>  
        plugins>  
    build>  
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    3 常用功能

    3.1 按需选择需要添加到最终 jar 包中依赖

    3.1.1 使用

    使用结合 & 标签打包时,可实现更灵活的依赖选择。它是以groupId:artifactId为标识,在filter内部可以使用 / 更细致地控制,既可以移除代码文件,也可以移除配置文件,示例如下:

    
    <configuration>
        <filters>
            <filter>
            	
            	<artifact>junit:junitartifact>
            	
            	<includes>
            		<include>junit/framework/**include>
            		<include>org/junit/**include>
            	includes>
            	
            	<excludes>
            		<exclude>org/junit/experimental/**exclude>
            		<exclude>org/junit/runners/**exclude>
            	excludes>
            filter>
            <filter>
            	 
                 <artifact>*:*artifact>
                 <excludes>
                   <exclude>META-INF/*.SFexclude>
                   <exclude>META-INF/*.DSAexclude>
                   <exclude>META-INF/*.RSAexclude>
                 excludes>
               filter>
        filters>
    configuration>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    3.1.2 使用

    使用 排除不需要的依赖,指定 groupId:artifactId 的标识,示例如下:

    <configuration>
        <artifactSet>
            <excludes>
                <exclude>classworlds:classworldsexclude>
                <exclude>junit:junitexclude>
                <exclude>jmock:*exclude>
                <exclude>*:xml-apisexclude>
                <exclude>org.apache.maven:lib:testsexclude>
                <exclude>log4j:log4j:jar:exclude>
            excludes>
        artifactSet>
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3.3.3 使用

    除了可以通过自定义的 filters 来过滤依赖,此插件还支持自动移除项目中没有使用到的依赖,以此来最小化 jar 包的体积,只需要添加一项配置即可。示例如下:

    建议maven-shade-plugin的版本为3.2.4,低版本会报错

    <configuration>
        <minimizeJar>trueminimizeJar>
    configuration>
    
    • 1
    • 2
    • 3

    3.2 重定位 class 文件

    如果最终的 jar 包被其他的项目所依赖的话,直接地引用此 jar 包中的类可能会导致类加载冲突,这是因为 classpath 中可能存在重复的 class 文件。为了解决这个问题,我们可以使用 shade 提供的重定位功能,把部分类移动到一个全新的包中。示例如下:

    涉及标签:
    <pattern>:原始包名
    <shadedPattern>:重命名后的包名
    <excludes>:原始包内不需要重定位的类,类名支持通配符
    
    <configuration>
        <relocations>
            <relocation>
                <pattern>org.codehaus.plexus.utilpattern>
                <shadedPattern>org.shaded.plexus.utilshadedPattern>
                <excludes>
                    <exclude>org.codehaus.plexus.util.xml.Xpp3Domexclude>
                    <exclude>org.codehaus.plexus.util.xml.pull.*exclude>
                excludes>
            relocation>
        relocations>
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在上述示例中,我们把 org.codehaus.plexus.util 包内的所有子包及 class 文件(除了 ~.xml.Xpp3Dom 和 ~.xml.pull 包下的所有 class 文件)重定位到了 org.shaded.plexus.util 包内。

    当然,如果包内的大部分类我们都不需要,一个个排除就显得很繁琐了。此时我们也可以使用 标签来指定我们仅需要的类,示例如下:

    <project>
        ...
        <relocation>
            <pattern>org.codehaus.plexus.utilpattern>
            <shadedPattern>org.shaded.plexus.utilshadedPattern>
            <includes>
                <include>org.codehaud.plexus.util.io.*include>
            includes>
        relocation>
        ...
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3.3 生成可执行 jar 包指定启动类

    使用 maven-plugin-shade 后,最终生成的 jar 包可以包含所有项目所需要的依赖。

    我们会想,能不能直接运行这个 uber-jar 呢?

    答案是当然可以,并且十分简单,只需要指定启动类,然后java -jar jar包就可以了。示例如下:

    <project>
        ...
        <configuration>
            <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                    <mainClass>cn.fileserver.HttpFileServermainClass>
                transformer>
            transformers>
        configuration>
        ...
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3.4 生成可执行 jar 包不指定启动类

    在打包后,有可能有多个mainClass,那么就可以在pom.xml中不指定启动类,然后通过java -cp jar包 全路径类名启动即可

    <project>
        ...
        <configuration>
            <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                    <mainClass>mainClass>
                transformer>
            transformers>
        configuration>
        ...
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3.5 定制 MANIFEST.MF 文件

    熟悉 jar 包的朋友们都知道,jar 包中在META-INF中默认会包含一个 MANIFEST.MF 文件
    在这里插入图片描述
    MANIFEST.MF

    Manifest-Version: 1.0
    Archiver-Version: Plexus Archiver
    Built-By: lvxy
    Created-By: Apache Maven 3.8.1
    Build-Jdk: 1.8.0_261
    Main-Class: cn.fileserver.HttpFileServer
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    里面描述了一些 jar 包的信息。使用 java 自带的 jar 命令打包的时候可以指定 MANIFEST.MF,其中也可以指定 Main-Class 来使得 jar 包可运行。那么使用 shade 来指定和直接在 MANIFEST.MF 文件中指定有什么区别呢?

    答案是没有区别,细心的读者会发现 标签的父标签是 有一个implementation属性,其值为 "~.ManifestResourceTransformer",意思是 Manifest 资源文件转换器。上述示例只自指定了启动类,因此 shade 会为我们自动生成一个包含 Main-Class 的 MANIFEST.MF 文件,然后在打 jar 包时指定这个文件。

    那如果我们想要完全定制 MANIFEST.MF 文件内容怎么办呢?我们可以使用标签,示例如下:

    <project>
        ...
        <configuration>
            <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                    <manifestEntries>
                        <Main-Class>cn.fileserver.HttpFileServerMain-Class>
                        <Build-Number>123Build-Number>
                    manifestEntries>
                transformer>
            transformers>
        configuration>
        ...
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    此时的 MANIFEST.MF

    Manifest-Version: 1.0
    Build-Number: 123
    Archiver-Version: Plexus Archiver
    Built-By: lvxy
    Created-By: Apache Maven 3.8.1
    Build-Jdk: 1.8.0_261
    Main-Class: cn.fileserver.HttpFileServer
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3.6 第三方的部分重命名

    比如我使用hutool包

    import cn.hutool.core.util.StrUtil;
    import cn.hutool.json.serialize.GlobalSerializeMapping;
    
    public class Main {
        public static void main(String[] args) {
            System.out.println(StrUtil.class.getPackage());
            System.out.println(GlobalSerializeMapping.class.getPackage());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    运行结果:

    package cn.hutool.core.util
    package cn.hutool.json.serialize
    
    • 1
    • 2

    使用relocation进行对部分包进行重命名:

    <configuration>
        ...
        <relocations>
            <relocation>
                <pattern>cn.hutool.corepattern>
                <shadedPattern>my.cn.hutool.coreshadedPattern>
            relocation>
        relocations>
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    打包后运行jar包,运行结果为:

    package my.cn.hutool.core.util
    package cn.hutool.json.serialize
    
    • 1
    • 2

    4 生成资源文件

    项目中涉及到的依赖可能会有它们所必需的资源文件,使用 shade 可以把它们聚合在同一个 jar 包中。

    默认地,shade 为我们提供了 12 个 ResourceTransformer 类:

    类名作用
    ApacheLicenseResourceTransformer防止 LICENSE 文件重复
    ApacheNoticeResourceTransformer准备合并的 NOTICE
    AppendingTransformer为某个资源文件附加内容
    ComponentsXmlResourceTransformer聚合 Plexus components.xml
    DontIncludeResourceTransformer防止包含指定的资源
    GroovyResourceTransformer合并 Apache Groovy 的扩展模块
    IncludeResourceTransformer添加项目中的文件为资源文件
    ManifestResourceTransformer自定义 MANIFEST 文件
    PluginXmlResourceTransformer聚合 Maven 的 plugin.xml 配置
    ResourceBundleAppendingTransformer合并 ResourceBundles
    ServicesResourceTransformer重定位且合并 META-INF/services 资源文件中的 class 文件.
    XmlAppendingTransformer为 XML 资源文件附加内容

    这里介绍一些常用的Transformer,
    更多的Transformer见:
    http://maven.apache.org/plugins/maven-shade-plugin/examples/resource-transformers.html

    4.1 ManifestResourceTransformer

    往MANIFEST文件中写入Main-Class是可执行包的必要条件。ManifestResourceTransformer可以轻松实现。

    <configuration>
    	<transformers>
    		<transformer
    			implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
    			<mainClass>com.lcifn.ApplicationmainClass>
    		transformer>
    	transformers>
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    4.2 AppendingTransformer

    用来处理多个jar包中存在重名的配置文件的合并,尤其是spring。

    <configuration>
    	<transformers>
    		<transformer
    			implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
    			<resource>META-INF/spring.handlersresource>
    		transformer>
    		<transformer
    			implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
    			<resource>META-INF/spring.schemasresource>
    		transformer>
    	transformers>
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    4.3 ServicesResourceTransformer

    JDK的服务发现机制是基于META-INF/services/目录的,如果同一接口存在多个实现需要合并 ,则可以使用此Transformer。

    <configuration>
      <transformers>
        <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
      transformers>
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5 原始构件与shade构件

    默认情况下,shade插件会覆盖基于项目的jar包,而生成包含所有依赖的jar包。但有时需要原始的jar包和shade后的jar包同时被部署,可以配置如下。

    <configuration>
      <shadedArtifactAttached>trueshadedArtifactAttached>
      
      <shadedClassifierName>execshadedClassifierName> 
    configuration>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    6 常见问题

    打包成功,运行报错SecurityException

    Error: A JNI error has occurred, please check your installation and try again
    Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for Manifest main attributes
            at sun.security.util.SignatureFileVerifier.processImpl(SignatureFileVerifier.java:330)
            at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier.java:263)
            at java.util.jar.JarVerifier.processEntry(JarVerifier.java:318)
            at java.util.jar.JarVerifier.update(JarVerifier.java:230)
            at java.util.jar.JarFile.initializeVerifier(JarFile.java:384)
            at java.util.jar.JarFile.ensureInitialization(JarFile.java:615)
            at java.util.jar.JavaUtilJarAccessImpl.ensureInitialization(JavaUtilJarAccessImpl.java:69)
            at sun.misc.URLClassPath$JarLoader$2.getManifest(URLClassPath.java:1011)
            at java.net.URLClassLoader.defineClass(URLClassLoader.java:451)
            at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
            at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
            at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
            at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
            at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:601)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    该错误原因常常为包的引用重复,产生了多余的.SF文件(这种打包方式造成,目前不清楚具体原因)

    删除jar包中META-INF下的.SF文件即可:

                                <filters>
                                    <filter>
                                        <artifact>*:*artifact>
                                        <excludes>
                                            <exclude>META-INF/*.SFexclude>
                                            <exclude>META-INF/*.DSAexclude>
                                            <exclude>META-INF/*.RSAexclude>
                                        excludes>
                                    filter>
                                filters>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    参考文章:
    https://blog.51cto.com/u_15127499/2672787
    https://blog.csdn.net/iflink/article/details/122389637

  • 相关阅读:
    Iview Tree组件点击标题展开
    【CMU15-445 Part-15】Query Planning & Optimization II
    GP09|公司赚的多,股票涨的好?
    线程的创建方式
    FreeRTOS学习记录--任务创建函数详解
    数字集成电路设计(四、Verilog HDL数字逻辑设计方法)(二)
    极智开发 | 讲解 React 组件三大属性之三:refs
    微信销售技巧和话术
    C语言 | Leetcode C语言题解之第187题重复的DNA序列
    双非硕的秋招路:长风破浪会有时
  • 原文地址:https://blog.csdn.net/weixin_43702146/article/details/126480018