Gradle打包可执行jar文件

(附加一个官网打包可执行jar文件地址:https://docs.gradle.org/current/userguide/building_java_projects.html#sec:java_packaging
,要打包可执行文件需添加manifest和Main-Class)
依赖情况

    dependencies {
        testImplementation group: 'junit', name: 'junit', version: '4.12'
        implementation('io.netty:netty-all:4.1.43.Final')
        implementation("com.google.guava:guava:28.1-jre")
    }

在根项目的build.gradle中,添加如下代码

jar {
    //详细信息参考 https://docs.gradle.org/current/dsl/org.gradle.api.tasks.bundling.Jar.html
    archivesBaseName = 'MiniRPC'//基本的文件名
    archiveVersion = '0.0.3' //版本
    manifest { //配置jar文件的manifest
        attributes(
                "Manifest-Version": 1.0,
                'Main-Class': 'com.mirs.minirpc.App' //指定main方法所在的文件
        )
    }
 //打包依赖包
    from {
        (configurations.runtimeClasspath).collect {
            it.isDirectory() ? it : zipTree(it)
        }
    }
}

这里踩了个坑,网上绝大多数文章在打包依赖的时候都是使用的configurations.runtime。使用compile引入的依赖,使用这种方式可以打包,但对于implementation引入的依赖,要使用configurations.runtimeClasspath才能把依赖打包进去。无论compile还是implementation引入依赖,configurations.runtimeClasspath都可以打包依赖。
此外对于testImplementation引入的依赖,则使用configurations.testRuntimeClasspath。
(参考文章 https://www.zhuyanbin.com/?p=654

打包后的jar文件


 
image.png

运行结果


 
image.png
 
 
0人点赞
 
随笔
 
 
 


作者:Giliver
链接:https://www.jianshu.com/p/5e2b7087429b
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原文地址:https://www.cnblogs.com/javalinux/p/14791160.html