0

我不知道如何在带有 kotlin DSL 的 gradle 构建中使用shadow插件。所有文档都使用 groovy dsl。

这是 build.gradle.kts 的内容:

import groovy.lang.GroovyObject
import org.gradle.jvm.tasks.Jar

plugins {
    // Apply the Kotlin JVM plugin to add support for Kotlin.
    id("org.jetbrains.kotlin.jvm") version "1.4.10"

    id("com.github.johnrengelman.shadow") version "6.1.0"
    application
}

allprojects {
    repositories {
        // Use jcenter for resolving dependencies.
        // You can declare any Maven/Ivy/file repository here.
        jcenter()
    }
    group = "com.example"
    version = "1.0-SNAPSHOT"
}

dependencies {
    // Align versions of all Kotlin components
    implementation(platform("org.jetbrains.kotlin:kotlin-bom"))

    // Use the Kotlin JDK 8 standard library.
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
}

application {
    mainClass.set("com.example.MainKt")
}


tasks.withType<Jar> {
    manifest {
        attributes(
                mapOf(
                    "ImplementationTitle" to project.name,
                    "Implementation-Version" to project.version)
        )
    }
}

这是内容src/main/kotlin/com/example/Main.kt

package com.example

fun main() {
    println("Hello world")
}

但是当我尝试这样做时gradle build,我收到了这个错误:

A problem was found with the configuration of task ':shadowJar' (type 'ShadowJar').
> No value has been specified for property 'mainClassName'.

我认为这很奇怪,因为我已经在application参数中输入了应用程序主类。

我试图添加这个:

tasks.withType<ShadowJar>() {
    mainClassName = "com.example.MainKt"
}

但是当我尝试使用此选项进行构建时,它会抱怨找不到ShadowJar类型。

  Line 22: tasks.withType<ShadowJar>() {
                          ^ Unresolved reference: ShadowJar

我在这里做错了什么?

4

2 回答 2

2

问题是我试图添加mainClassNameShadowJar任务中,它应该已经添加到application函数中。像这样:

application {
    val name = "com.cognite.ingestionservice.MainKt"
    mainClass.set(name)

    // Required by ShadowJar.
    mainClassName = name
}

mainClassName属性已弃用,但 ShadowJar 从6.1.0版本开始仍需要该属性。

mainClass.set()添加时不需要mainClassName,但它在 gradle 6.7 的文档中,所以我还是添加了它。

于 2020-11-02T11:34:29.240 回答
1

我建议在您的简单情况下配置默认shadowJarjar任务(不是所有任务ShadowJarJar类型,因为您没有创建其他实例)。

tasks {
    jar {
        manifest {
            attributes(
                mapOf(
                    "Main-Class" to "com.example.MainKt", //will make your jar (produced by jar task) runnable 
                    "ImplementationTitle" to project.name,
                    "Implementation-Version" to project.version)
            )
        }
    }
    shadowJar {
        manifest.inheritFrom(jar.get().manifest) //will make your shadowJar (produced by jar task) runnable
    }
}

application {
    mainClassName = "com.example.MainKt" //will make run & runShadow tasks work. Have no idea why it can't take main class from jar/shadowJar manifests
}

于 2020-10-30T21:56:42.330 回答