设为首页 加入收藏

TOP

WebSocket无法注入属性
2023-09-23 15:44:17 】 浏览:78
Tags:WebSocket

踩坑一:

原因:

是因为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服务器中自动注入

  1. 错误方法,这样无法从容器中获取
@ServerEndpoint(value = "/chat/{username}")
@Service
public class WebSocketServer {

    @Resource // @Autowired
    private RabbitTemplate rabbitTemplate;  //null
}
  1. 解决:使用上下文获取
@ServerEndpoint(value = "/chat/{username}")
@Service
public class WebSocketServer {

    /*
     * 提供一个spring context上下文(解决方案)
     */
    private static ApplicationContext context;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketServer.context = applicationContext;
    }
}
  1. 在启动类中传入上下文
@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);
    }
}
  1. 在使用的地方通过上下文去获取服务context.getBean();
public void sendSimpleQueue(String message) {
    String queueName = "talk";
    // 在使用的地方通过上下文去获取服务context.getBean();
    RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
    
    rabbitTemplate.convertAndSend(queueName, message);
}
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇快速搭建linux centos 部署环境及.. 下一篇spring security为啥是个垃圾框架..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目