Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

websocket端点无法获取spring的组件

@ServerEndpoint(value = "/chat/{token}")
@Component
public class ChatEndpoint {
 //用来存储每一个客户端对象对应的ChatEndpoint对象
 private static Map onlineUsers = new ConcurrentHashMap<>();
 @Autowired
 private MessageService messageService;
 }

这是一个websocket的端点,无法获取的组件messageService,当然这个组件在controller可以获得的,不是它的问题。

@Service
public class MessageServiceImpl implements MessageService {}

我应该才能获取得到在websocket端点获取spring的组件呢?

问题描述

问题出现的环境背景及自己尝试过哪些方法

相关代码

粘贴代码文本(请勿用截图)

你期待的结果是什么?实际看到的错误信息又是什么?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

自己的问题自己解决。

@Configuration
public class WebSocketConfig {
    @Bean
 //注入ServerEndpointExporter,自动注册使用@ServerEndpoint注解的
 public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
    //解决websocket注入问题
 @Autowired
 public void setMessageService(MessageService messageService){
        ChatEndpoint.messageService = messageService;
    }
}
@ServerEndpoint(value = "/chat/{token}")
@Component
public class ChatEndpoint {
    //用来存储每一个客户端对象对应的ChatEndpoint对象
 private static Map<String,ChatEndpoint> onlineUsers = new ConcurrentHashMap<>();
    public static MessageService messageService;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...