首页 > 解决方案 > gradle 创建 jar 不适用于“实现”依赖项

问题描述

我是 gradle 的新手,并试图从一个简单的 hello world java grpc生成一个 jar ,下面是我的 build.gradle

plugins {
    id 'application'
    id 'com.google.protobuf' version '0.8.12'
    id 'idea'
    id 'java'
}

version '1.0'

sourceCompatibility = 1.8

repositories {
    mavenLocal()
    maven { // The google mirror is less flaky than mavenCentral()
        url "https://maven-central.storage-download.googleapis.com/repos/central/data/" }
    mavenCentral()
}

dependencies {
    implementation 'io.grpc:grpc-netty-shaded:1.29.0'
    implementation 'io.grpc:grpc-protobuf:1.29.0'
    implementation 'io.grpc:grpc-stub:1.29.0'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}


protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.11.0"
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.29.0'
        }
    }
    generateProtoTasks {
        all()*.plugins {
            grpc {}
        }
    }
}

sourceSets {
    main {
        java {
            srcDirs 'build/generated/source/proto/main/grpc'
            srcDirs 'build/generated/source/proto/main/java'
        }
    }
}

startScripts.enabled = false

task helloWorldServer(type: CreateStartScripts) {
    mainClassName = 'com.javagrpc.HelloWorldServer'
    applicationName = 'hello-world-server'
    outputDir = new File(project.buildDir, 'tmp')
    classpath = startScripts.classpath
}

applicationDistribution.into('bin') {
    from(helloWorldServer)
    fileMode = 0755
}

distZip.shouldRunAfter(build)

jar {
    manifest {
        attributes 'Main-Class': 'com.examples.javagrpc.HelloWorldServer',
        'Class-Path': configurations.runtime.files.collect { "lib/$it.name" }.join(' ')
    }

    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    }
    exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA'
}

当我运行任务“gradle jar”时,我开始遇到问题,当我运行 jar 时,它会在 build/libs 中构建一个 jar,它失败了,java.lang.NoClassDefFoundError: io/grpc/BindableService 因为我解压了 jar 并且没有在其中找到 grpc 依赖项。我尝试直接运行生成的文件

./build/install/java-grpc/bin/hello-world-server

它按预期工作。为了解决 jar 问题,我决定将上述依赖项从implementation更改为api,如下所示。

dependencies {
    api 'io.grpc:grpc-netty-shaded:1.29.0'
    api 'io.grpc:grpc-protobuf:1.29.0'
    api 'io.grpc:grpc-stub:1.29.0'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

现在一切都按预期工作,依赖项在 jar 中,我可以运行 jar。但是我不确定我是否应该在我的依赖项中使用api,因为官方示例没有使用它?也许我没有正确生成 jar,它可以通过依赖项实现生成,任何帮助或指针都非常感谢。

标签: javagradlegrpcgrpc-java

解决方案


问题是jar您使用的任务修改没有利用新的依赖配置。

与其从中收集依赖项,不如从uber JAR 中compile收集依赖项。runtimeClasspath毕竟,为了运行,它还需要声明所有依赖implementationruntimeOnly。请参阅文档以更好地了解这些配置之间的关系。

jar {
    ...
    from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
    ...
}

推荐阅读