WebSocket无法注入属性

打印 上一主题 下一主题

主题 833|帖子 833|积分 2499

踩坑一:
原因:

是因为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. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

涛声依旧在

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表