Spring Boot打包Jar后WebSocket依赖缺失报错求助
问题与解决方案
问题场景
手动导入spring-websocket-5.2.12.RELEASE.jar并配置Maven system依赖后,WebSocket功能在IDEA中正常运行,但打包成Jar后启动报错,核心错误为:
java.lang.ClassNotFoundException: org.springframework.web.socket.server.standard.ServerEndpointExporter
相关配置代码如下:
pom.xml中的system依赖
<dependency> <groupId>websoc</groupId> <artifactId>websoc</artifactId> <version>5.2.12</version> <scope>system</scope> <systemPath>${pom.basedir}/libs/spring-websocket-5.2.12.RELEASE.jar</systemPath> </dependency>
WebSocketConfig配置类
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration @EnableWebSocket public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
MyWebSocket业务类
import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; @Component @ServerEndpoint(value = "/websocket/{name}") public class MyWebSocket { @OnOpen public void onOpen(@PathParam("name") String name, Session session) { System.out.println("有新连接加入!" + name); } @OnClose public void onClose() { System.out.println("有一连接关闭!"); } @OnMessage public void onMessage(String message) { } @OnError public void onError(Throwable error) { System.out.println("发生错误"); } }
解决方案
1. 替换system依赖为官方仓库依赖
system scope的依赖不会被Maven打包到最终Jar中,这是运行时类找不到的根本原因。删除手动导入的Jar包,将pom.xml中的依赖替换为Maven中央仓库的官方依赖:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>5.2.12.RELEASE</version> </dependency>
如果是Spring Boot项目,更推荐使用starter依赖自动管理版本,避免冲突:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2. 清理并重新构建项目
执行以下Maven命令完成清理、编译和打包:
mvn clean package
然后运行打包后的Jar文件:
java -jar your-project.jar
3. 排查依赖冲突(若替换后仍有问题)
使用Maven命令查看依赖树,检查是否存在版本冲突:
mvn dependency:tree
如果发现其他依赖引入了不同版本的spring-websocket,通过<exclusions>标签排除冲突依赖:
<dependency> <!-- 存在冲突的依赖 --> <groupId>xxx</groupId> <artifactId>xxx</artifactId> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> </exclusion> </exclusions> </dependency>
内容的提问来源于stack exchange,提问作者yrmkye
相关产品推荐
相关产品推荐

