我使用 eclipse paho mqtt library 创建了一个小型 mqtt 应用程序在 Kotlin 中使用 Intellij IDE 中的 Gradle。通过 Intellij 运行它时它运行良好,但是当我构建它并运行创建的 jar 文件时,我收到 NoClassDefFoundError
错误。
从我看到的其他问题来看,它看起来与类路径有关,但我不确定如果这确实是问题,需要做什么,因为我使用的是 gradle 而不是库的 jar 文件.
我正在关注这个tutorial
这是我的 gradle 文件
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.4.31'
id 'application'
}
group = 'me.package'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
maven {
url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
}
}
dependencies {
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit'
}
test {
useJUnit()
}
compileKotlin {
kotlinOptions.jvmTarget = '1.8'
}
compileTestKotlin {
kotlinOptions.jvmTarget = '1.8'
}
application {
mainClassName = 'com.publisher.MainKt'
}
tasks.jar {
manifest {
attributes 'Main-Class': 'com.publisher.MainKt'
}
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
}
还有我的 MainKt 文件
package com.publisher
import org.eclipse.paho.client.mqttv3.*
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import java.io.File
fun main(args: Array<String>) {
val client = MqttClient("tcp://192.168.0.55:1883","publisher", MemoryPersistence())
val connOpts = MqttConnectOptions()
connOpts.isCleanSession = false
connOpts.isAutomaticReconnect = true
client.setCallback(object: MqttCallback {
override fun connectionLost(cause: Throwable?) {
println("Connection lost")
println(cause!!.message)
}
override fun messageArrived(topic: String?, message: MqttMessage?) {
println("Message Received for topic: $topic")
println("Message: ${message!!.payload}")
}
override fun deliveryComplete(token: IMqttDeliveryToken?) {
println("Message delivered")
}
})
try{
client.connect(connOpts)
println("Connected")
client.subscribe("config/+", 1) { topic, message ->
println("Getting configuration for $message")
val path = System.getProperty("user.dir")
val file = File("$path/${message}.json")
if(file.exists()){
client.publish("/devices/ + $message + /config", MqttMessage(file.readBytes()))
}
}
}catch (e: MqttException){
println("Error: ${e.localizedMessage}")
e.printStackTrace()
}
}
最佳答案
您启动应用程序的方式不包括依赖项,这意味着您的 MQTT 驱动程序和 Kotlin 依赖项不包括在内。
执行以下操作:
gradle distZip
# alternatively
gradle distTar
这将创建一个包含所有依赖项和启动脚本的 zip/tar 文件。使用它来启动您的应用程序。
关于java - ClassNotFoundException 运行 jar 文件时但在 Intellij 中运行良好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66629642/