1. 首页 >  小程序定制 >  WebSocket无法注入属性

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
    

    }

  2. 解决:使用上下文获取

    @ServerEndpoint(value = “/chat/{username}”) @Service public class WebSocketServer {

    /*
     * 提供一个spring context上下文(解决方案)
     */
    private static ApplicationContext context;
    
    
    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketServer.context = applicationContext;
    }
    

    }

  3. 在启动类中传入上下文

    @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); } }

  4. 在使用的地方通过上下文去获取服务context.getBean();

    public void sendSimpleQueue(String message) { String queueName = “talk”; // 在使用的地方通过上下文去获取服务context.getBean(); RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);

    rabbitTemplate.convertAndSend(queueName, message);
    

    }

/xiao-cheng-xu-ding-zhi/websocketwu-fa-zhu-ru-shu-xing-725.html