Springboot集成Websocket不能使用@Autowired注入service

在springboot使用websocket过程中,需要使用到@Autowired注入service

按照平时的方法注入:

@ServerEndpoint(value = "/websocket/{name}")
@Component
public class WebSocketService {
	@Autowired
    ChatRecodeService chatRecodeService;

控制台报了空指针的异常


后来想了一下,会不会跟 @Autowired注解静态对象 实现的方法一样,尝试了一下:

@ServerEndpoint(value = "/websocket/{name}")
@Component
public class WebSocketService {
	private static ChatRecodeService chatRecodeService;

    @Autowired
    public void setChatRecodeService(ChatRecodeService chatRecodeService) {
        WebSocketService.chatRecodeService = chatRecodeService;
    }

发现通过 @Autowired注解setter方法 这种方式是可以解决空指针的问题。

@ServerEndpoint(value = "/websocket/{name}")
@Component
public class WebSocketService {
	private static ChatRecodeService chatRecodeService;

    @Autowired
    public WebSocketService (ChatRecodeService chatRecodeService) {
        WebSocketService.chatRecodeService = chatRecodeService;
    }

但是通过 @Autowired 注解构造函数 这种方式却不能解决这个错误。


找了一下类似的博客,发现原因是:

spring管理的是单例,而websocket管理的多对象,使用websocket每一次连接都会创建一个websocket对象

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
SpringBoot集成WebSocket是指在SpringBoot项目中使用WebSocket技术来实现后台向前端推送信息的功能。通过集成WebSocket,可以实现实时的双向通信,使后端能够主动向前端推送消息。 要实现SpringBoot集成WebSocket,首先需要创建一个SpringBoot项目,并引入WebSocket依赖。可以在pom.xml文件中添以下依赖: ``` <!-- WebSocket dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>2.7.12</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.7.12</version> </dependency> ``` 然后,需要在SpringBoot的配置类上添@EnableWebSocket注解,启用WebSocket功能。同时,可以创建一个WebSocket处理器类,用于处理WebSocket连接和消息的处理逻辑。 在启动项目后,可以通过访问http://localhost:8081/demo/toWebSocketDemo/{cid}来跳转到页面,然后就可以和WebSocket进行交互了。通过WebSocket连接,后台可以向前端主动推送消息,实现实时的双向通信。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringBoot 集成WebSocket详解](https://blog.csdn.net/qq_42402854/article/details/130948270)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值