我正在编写一个桌面Java应用程序作为Web服务客户端。我想使用WebSocket从服务器实现通知“回调”。
我正在使用Spring框架的WebSocketStompClient。以下代码段显示了如何对其进行初始化:
import org.springframework.web.socket.messaging.WebSocketStompClient;
import org.springframework.web.socket.sockjs.client.SockJsClient;
import org.springframework.web.socket.sockjs.client.Transport;
import org.springframework.web.socket.sockjs.client.WebSocketTransport;
...
List<Transport> transports = new ArrayList<>();
transports.add(new WebSocketTransport(new StandardWebSocketClient()));
stompClient = new WebSocketStompClient(new SockJsClient(transports));
...
如果我在IntelliJ IDE中运行它,则可以完美运行,但是,如果我通过命令行“ java -cp my.jar MyPackage.MyMainClass”运行,它将失败并显示以下消息:
Error: Unable to initialize main class MyMainClass
Caused by: java.lang.NoClassDefFoundError: org/springframework/web/socket/client/WebSocketClient
以上是由Java SE 12.0.2产生的。如果我使用Java SE 1.8运行它,则错误消息将是:
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError:
org/springframework/web/socket/client/WebSocketClient
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.privateGetMethodRecursive(Unknown Source)
at java.lang.Class.getMethod0(Unknown Source)
at java.lang.Class.getMethod(Unknown Source)
at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
双方java.lang.NoClassDefFoundError
并getDeclaredMethods0(Native Method)
suggsted一个本机模块(一个DLL)丢失。
以下是我的Gradle脚本:
dependencies {
implementation project(':logman-common')
implementation 'org.springframework:spring-web:5.2.2.RELEASE'
implementation 'org.springframework:spring-websocket:5.2.2.RELEASE'
implementation 'org.springframework:spring-messaging:5.2.2.RELEASE'
... // other unrelated dependencies, such as GUI
}
我不认为这是由于缺少JAR所致。我试过了:
tyrus-standalone-client
到依赖项列表,或StandardWebSocketClient
替代SockJsClient
,但是错误仍然存在。
我猜我的操作系统(Win10)中缺少一些本机库,但这不能解释为什么我可以在IntelliJ中运行它。
你能让我知道缺少了什么吗?或者我该如何解决?谢谢!
尝试创建一个包含所有依赖项和类的胖子。
更新build.gradle
脚本到下面给出的:
apply plugin: 'java'
version = '...'
sourceCompatibility = 1.8
targetCompatibility = 1.8
// to create a fat jar.
jar {
manifest {
attributes "Main-Class": "MyPackage.MyMainClass"
}
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
dependencies {
implementation project(':logman-common')
implementation 'org.springframework:spring-web:5.2.2.RELEASE'
implementation 'org.springframework:spring-websocket:5.2.2.RELEASE'
implementation 'org.springframework:spring-messaging:5.2.2.RELEASE'
... // other unrelated dependencies, such as GUI
}
它将在build/libs
您的根项目的中生成一个可执行的胖子jar,其中将包括所有项目文件(包括您的所有依赖项,资源文件,.class文件等)。
注意:对于较早版本的Gradle,请使用此configurations.compile.collect
代替configurations.runtimeClasspath.collect
。
您只需要使用以下命令运行jar: java -jar <project-version>.jar
这应该可以解决您的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句