@Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myWebSocketHandler(), "/ws").setAllowedOrigins("*"); } @Bean public MyWebSocketHandler myWebSocketHandler() { return new MyWebSocketHandler(); } public class MyWebSocketHandler extends TextWebSocketHandler { private List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); System.out.println("WebSocket 连接已建立"); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); System.out.println("WebSocket 连接已关闭"); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { System.out.println("接收到消息:" + message.getPayload()); sendMessageToAllUsers("服务器收到消息:" + message.getPayload()); } public void sendMessageToAllUsers(String message) throws IOException { for (WebSocketSession session : sessions) { session.sendMessage(new TextMessage(message)); } } } } 报错 org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'defaultSockJsTaskScheduler' is expected to be of type 'org.springframework.scheduling.TaskScheduler' but was actually of type 'org.springframework.beans.factory.support.NullBean'
时间: 2024-02-14 21:07:40 浏览: 79
这个异常通常出现在Spring框架中,是因为在WebSocket配置的过程中,Spring期望得到一个类型为`org.springframework.scheduling.TaskScheduler`的Bean,但实际上得到的是`org.springframework.beans.factory.support.NullBean`类型的Bean。
这个问题可能是因为在你的代码中缺少了一些配置,或者某些配置有误。你可以尝试在`WebSocketConfig`类中添加一个`@Bean`注解,用于创建一个`TaskScheduler`类型的Bean,并在`WebSocketConfigurer`接口的实现方法中使用它。
例如:
```
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myWebSocketHandler(), "/ws").setAllowedOrigins("*");
}
@Bean
public MyWebSocketHandler myWebSocketHandler() {
return new MyWebSocketHandler();
}
@Bean
public TaskScheduler taskScheduler() {
return new ConcurrentTaskScheduler();
}
public class MyWebSocketHandler extends TextWebSocketHandler {
// ...
}
}
```
在这个例子中,我们添加了一个名为`taskScheduler`的Bean,并使用`ConcurrentTaskScheduler`作为它的实现类。这个Bean可以满足Spring期望得到的`TaskScheduler`类型的要求,从而解决了异常的问题。
阅读全文