springboot中websocket服务怎么调用其他类的方法

前言:

        之前有写过一个springboot整合websocket的博客(SpringBoot 集成websocket_清泉影月的博客-CSDN博客),最开始的使用场景就是用websocket发消息给其他长连接;后来新增了一个需求:长连接的某些信息要保存到数据库。想着应该比较简单,写个类方法注入到websocket服务里面调用就行了,结果发现报错,本地调试发现注入的类居然是个null。研究了一番,处理起来就是:启动类启动时把上下文直接配置到 websocket的服务里面,websocket服务调用其他类方法时从上下文中获取。

一、启动类设置上下文到 websocket

@SpringBootApplication
public class TableApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(TableApplication.class, args);
        WebSocketServer.setApplicationContext(context);
    }

}

WebSocketServer是websocket的服务类。

二、websocket服务类调用其他类方法

websocket服务类新增以下配置,跟启动类相呼应

public class WebSocketServer {

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

}

websocket服务类调用其他类方法样例如下:

    private void saveInfoToDb(WebsocketMsg websocketMsg) {
        SocketTableConnService socketTableConnService = applicationContext.getBean(SocketTableConnService.class);
        socketTableConnService.saveInfoToDb(websocketMsg);
    }

猜你喜欢

转载自blog.csdn.net/qingquanyingyue/article/details/125708526