java - 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,它可以通过依赖项实现生成,任何帮助或指针都非常感谢。
解决方案
问题是jar
您使用的任务修改没有利用新的依赖配置。
与其从中收集依赖项,不如从uber JAR 中compile
收集依赖项。runtimeClasspath
毕竟,为了运行,它还需要声明所有依赖implementation
项runtimeOnly
。请参阅文档以更好地了解这些配置之间的关系。
jar {
...
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
...
}
推荐阅读
- python - 如何在 Odoo 或 OpenERP 中关联来自不同模型的两个字段?
- python - 如何使用张量调用 `tf.nn.avg_pool2d()`?
- html - 根据另一个 css 属性值更改内容样式
- wordpress - 自动从 Google 获取图片以获得 WooCommerce 产品标题
- php - 如何在codeception中从文件中获取数据
- mysql - 刚刚安装了 Laravel Sail。如何连接数据库?
- ios - 恢复购买完成结果 (iOS)?
- javascript - 通过特定邀请加入时为新成员赋予角色
- angular - 需要在 nz transfer 中显示两个不同的数据
- javascript - 如何在浏览器中拼接/连接/合并两个 mp4 blob?