踩坑一:
原因:
是因为Spring对象的创建都是以单例模式创建的,在启动时只创建一次WebSocket。而WebSocketServer在每个连接请求到来时,都会new一个对象。所以当你启动项目时,你想要注入的对象已经注入进去,但是当用户连接是,新创建的websocket对象没有你要注入的对象,所以会报NullPointerException
解决:
通过static关键字让webSocketService属于WebSocketServer类- private static WebSocketService webSocketService; //通过static关键字让webSocketService属于WebSocketServer类
- @Autowired//注入到WebSocketServer类的webSocketService属性里
- public void setKefuService(WebSocketService webSocketService){
- WebSocketServer.webSocketService= webSocketService;
- }
复制代码 踩坑二:
使用@ServerEndpoint声明的websocket服务器中自动注入
- @ServerEndpoint(value = "/chat/{username}")
- @Service
- public class WebSocketServer {
- @Resource // @Autowired
- private RabbitTemplate rabbitTemplate; //null
- }
复制代码- @ServerEndpoint(value = "/chat/{username}")
- @Service
- public class WebSocketServer {
- /*
- * 提供一个spring context上下文(解决方案)
- */
- private static ApplicationContext context;
- public static void setApplicationContext(ApplicationContext applicationContext) {
- WebSocketServer.context = applicationContext;
- }
- }
复制代码- @SpringBootApplication
- public class TalkApplication {
- public static void main(String[] args) {
- //解决springboot和websocket之间使用@autowired注入为空问题
- ConfigurableApplicationContext applicationContext =
- SpringApplication.run(TalkApplication.class, args);
- //这里将Spring Application注入到websocket类中定义的Application中。
- WebSocketServer.setApplicationContext(applicationContext);
- }
- }
复制代码
- 在使用的地方通过上下文去获取服务context.getBean();
- public void sendSimpleQueue(String message) {
- String queueName = "talk";
- // 在使用的地方通过上下文去获取服务context.getBean();
- RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
-
- rabbitTemplate.convertAndSend(queueName, message);
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |