gradle打包fat jar记录

这篇博客记录了如何使用Gradle打包包含所有依赖的Fat Jar。在不使用Fat Jar模式时,依赖项可能不会被包含在同一包中,导致运行时错误,例如缺少log4j库。文中提供了两种Gradle打包Fat Jar的方法,旨在方便日后参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用gradle项目打包jar包的时候如果不使用fat jar的打包模式会造成dependency没有全部被打在一个包中的结果

譬如在denpendency的情况为如下的情况时

dependencies {

    testCompile group: 'junit', name: 'junit', version: '4.12'

    compile fileTree(dir:'libs',include:['*.jar'])
    implementation group: 'commons-validator', name: 'commons-validator', version: '1.4.0'
    implementation group: 'commons-io', name: 'commons-io', version: '2.6'
    compile group: 'org.apache.commons', name: 'commons-pool2', version: '2.0'
    testCompile group: 'junit', name: 'junit', version: '4.12'
    implementation 'junit:junit:4.12'
    implementation group: 'com.google.protobuf', name: 'protobuf-java-util', version: '3.10.0'
    implementation group: 'com.googlecode.protobuf-java-format', name: 'protobuf-java-format', version: '1.2'

    //lombok
    compile group: 'org.projectlombok', name: 'lombok', version: '1.18.12'
    annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.18.12'
    implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.30'
    implementation group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.30'


    implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.12.1'
    implementation group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.12.1'

    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.11'
    implementation group: 'io.netty', name: 'netty-all', version: '4.1.59.Final'
    implementation group: 'io.grpc', name: 'grpc-all', version: "$ioGrpcVersion"
    implementation group: 'io.grpc', name: 'grpc-netty-shaded', version: "$ioGrpcVersion"

}

如果不使用fat jar的打包执行后会出现找不到log4j包的错误

以下提供两种打fatJar的方式

jar {
    manifest {
        attributes "Main-Class": 'com.foo.bar.Main'
    }

    from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
}
task fatJar(type: Jar) {
    manifest.from jar.manifest
    classifier = 'all'
    from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    } {
        exclude "META-INF/*.SF"
        exclude "META-INF/*.DSA"
        exclude "META-INF/*.RSA"
    }
    with jar
}

代码很简单,只是记录一下以便下次直接使用就不多做解释了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值