4

我一直在尝试为我的 Kotlin/Java Ktor 项目创建一个可执行的 JAR。使用我的 gradle 脚本创建实际的 JAR 很简单,但无论出于何种原因,我都无法弄清楚如何克服错误消息:“JAR 文件:找不到主类 routing.MainKt”。我的 Kotlin 主函数位于包路由中名为 Main.kt 的文件中。下面是我的 gradle 文件。我究竟做错了什么?

buildscript {
   ext.kotlin_version = '1.2.21'
   ext.ktorVersion = '0.9.0'

repositories {
    mavenCentral()
}
dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}

apply plugin: 'java'
apply plugin: 'kotlin'

sourceCompatibility = 1.8
compileKotlin {
  kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
  kotlinOptions.jvmTarget = "1.8"
}

kotlin {
  experimental {
     coroutines "enable"
  }
}

jar {
  manifest {
     attributes 'Main-Class': "routing.MainKt"
  }

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

repositories {
  mavenCentral()
  jcenter()
  maven { url "https://dl.bintray.com/kotlin/kotlinx" }
  maven { url "https://dl.bintray.com/kotlin/ktor" }
  maven { url "http://repository.jetbrains.com/kotlin-nosql" }
  maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
}

dependencies {
  //Core Ktor libs
  compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
  compile "io.ktor:ktor-server-core:$ktorVersion"
  compile "io.ktor:ktor-server-netty:$ktorVersion"
  compile "io.ktor:ktor-freemarker:$ktorVersion"
  compile "io.ktor:ktor-locations:$ktorVersion"
  ...Other libs
}

编辑:当我在生成的 jar 上运行 jar tf 时,我得到以下相关信息:

routing/MainKt$chartsxyzApplication$5.class
routing/MainKt$chartsxyzApplication$5$1.class
routing/MainKt$chartsxyzApplication$4.class
routing/MainKt$chartsxyzApplication$4$1.class
routing/MainKt.class
routing/MainKt$redirect$1.class
routing/MainKt$chartsxyzApplication$5$2.class
routing/MainKt$chartsxyzApplication$2.class
routing/MainKt$chartsxyzApplication$1.class
routing/MainKt$chartsxyzApplication$3.class
routing/MainKt$main$1.class

Edit2:这是 Main.kt 的基础知识

package routing

import io.ktor.application.*
...

@location("/")
class Index
... A bunch of other locations

fun main(args: Array<String>) {
   embeddedServer(Netty, 8080, module = Application::chartsApplication).start()
}

fun Application.chartsApplication(){
   ...
}

suspend fun ApplicationCall.redirect(location: Any) {
   ...
}

fun ApplicationCall.refererHost() = request.header(HttpHeaders.Referrer)?.let { URI.create(it).host }
4

2 回答 2

1

这是使用 shadowjar 插件的替代方法。

task fatJar(type: Jar) {
    manifest {
        attributes 'Implementation-Title': project.name,
                'Implementation-Version': version,
                'Main-Class': 'class.path.to.MainKt'
    }
    baseName = project.name
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    exclude 'META-INF/*.RSA', 'META-INF/*.SF', 'META-INF/*.DSA'
    with jar
}
于 2018-02-01T15:04:06.377 回答
0

我认为对你来说最简单的方法是使用shadowjar 插件

它会将您所有的库包含到您的 jar 中。

于 2018-01-26T15:39:15.070 回答