SpringBoot 集成 WebSocket 后 WebSocketServer 中注入 Mapper 为空

1.在启动类中向 WebSocketServer 中注入 ApplicationContext(WebSocket服务已集成,若未集成,可参考SpringBoot 超简单集成 WebSocket)

@SpringBootApplication
public class WebSocketApplication {
    public static void main(String[] args) {
        SpringApplication sa= new SpringApplication(WebSocketApplication .class);
        ConfigurableApplicationContext cac= sa.run(args);
        WebSocketServer.setApplicationContext(cac);
    }
}

2.在 WebSocketServer 中通过 ApplicationContext.getBean() 获取 bean

//解决无法注入mapper问题
public static void setApplicationContext(ApplicationContext applicationContext) {
    WebSocketServer.applicationContext = applicationContext;
}

3.注入 Mapper

//实例化bean
DemoMapper demoMapper = applicationContext.getBean(DemoMapper.class);

4.完整 WebSocketServer 示例代码

package com.ymw.system.service.websocket;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ymw.common.utils.DateUtils;
import com.ymw.common.utils.redis.RedisUtils;
import com.ymw.system.domain.vehicle.FactoryHardwareEquipment;
import com.ymw.system.mapper.vehicle.FactoryHardwareEquipmentMapper;
import com.ymw.system.service.vehicle.IFactoryHardwareEquipmentLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
@ServerEndpoint("/screen/webSocket/{sid}")
public class WebSocketServer {

    private Session session;

    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    private String sid;

    private static ApplicationContext applicationContext;

    @Autowired
    private DemoMapper demoMapper;

    //解决无法注入 mapper 问题
    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketServer.applicationContext = applicationContext;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        this.sid = sid;
        webSocketSet.add(this);
        log.info("[WebSocket消息]有新的连接,总数:{}", webSocketSet.size());
    }

    /**
     * 注入 Mqpper 示例
     */
    private void onlineStatus(String sid, String remarks, Integer status) {
        //实例化bean
        demoMapper = applicationContext.getBean(DemoMapper .class);
		Demo demo= new Demo();
		demo.setName("示例");
        demoMapper.insertLog(demo);
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("[WebSocket消息]连接断开,总数:{}", webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("[WebSocket消息]收到客户端发来的消息:{}", message);
    }

    /**
     * 发送消息
     *
     * @param message 消息内容
     * @param sid     连接sid
     * @return 结果(成功,失败)
     */
    public String sendMessage(String message, String sid) {
        String flag = "失败";
        for (WebSocketServer webSocket : webSocketSet) {
            log.info("[WebSocket消息]向客户端发送消息:message={}", message);
            try {
                // 针对不同的连接推送数据
                if (StringUtils.equals(webSocket.sid, sid)) {
                    webSocket.session.getBasicRemote().sendText(message);
                    flag = "成功";
                }
            } catch (IOException e) {
                log.info("WebSocket 出错了!!!");
                e.printStackTrace();
            }
        }
        return flag;
    }

}

你可能感兴趣的:(WebSocket,spring,boot,websocket,java)