WebSocket无法注入属性

[复制链接]
发表于 2023-9-19 17:01:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
踩坑一:
原因:

是因为Spring对象的创建都是以单例模式创建的,在启动时只创建一次WebSocket。而WebSocketServer在每个连接请求到来时,都会new一个对象。所以当你启动项目时,你想要注入的对象已经注入进去,但是当用户连接是,新创建的websocket对象没有你要注入的对象,所以会报NullPointerException
解决:

通过static关键字让webSocketService属于WebSocketServer类
  1. private static WebSocketService webSocketService; //通过static关键字让webSocketService属于WebSocketServer类
  2. @Autowired//注入到WebSocketServer类的webSocketService属性里
  3. public void setKefuService(WebSocketService webSocketService){
  4.     WebSocketServer.webSocketService= webSocketService;
  5. }
复制代码
踩坑二:
使用@ServerEndpoint声明的websocket服务器中自动注入


  • 错误方法,这样无法从容器中获取
  1. @ServerEndpoint(value = "/chat/{username}")
  2. @Service
  3. public class WebSocketServer {
  4.     @Resource // @Autowired
  5.     private RabbitTemplate rabbitTemplate;  //null
  6. }
复制代码

  • 解决:使用上下文获取
  1. @ServerEndpoint(value = "/chat/{username}")
  2. @Service
  3. public class WebSocketServer {
  4.     /*
  5.      * 提供一个spring context上下文(解决方案)
  6.      */
  7.     private static ApplicationContext context;
  8.     public static void setApplicationContext(ApplicationContext applicationContext) {
  9.         WebSocketServer.context = applicationContext;
  10.     }
  11. }
复制代码

  • 在启动类中传入上下文
  1. @SpringBootApplication
  2. public class TalkApplication {
  3.     public static void main(String[] args) {
  4.         //解决springboot和websocket之间使用@autowired注入为空问题
  5.         ConfigurableApplicationContext applicationContext =
  6.                 SpringApplication.run(TalkApplication.class, args);
  7.         //这里将Spring Application注入到websocket类中定义的Application中。
  8.         WebSocketServer.setApplicationContext(applicationContext);
  9.     }
  10. }
复制代码

  • 在使用的地方通过上下文去获取服务context.getBean();
  1. public void sendSimpleQueue(String message) {
  2.     String queueName = "talk";
  3.     // 在使用的地方通过上下文去获取服务context.getBean();
  4.     RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
  5.    
  6.     rabbitTemplate.convertAndSend(queueName, message);
  7. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表