Bootstrap

SpringBoot中WebSocket使用@Autowired注入出现空指针异常java.lang.NullPointerException: null

1、问题描述

产生空指针的主要原因
由于Spring管理的对象都是单例的(singleton),和 WebSocket(多对象)相冲突

在这里插入图片描述

在这里插入图片描述

2、解决办法

2.1引入spring context上下文

/*
* 引入Spring Context上下文
*/
private static ApplicationContext applicationContext;

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

在这里插入图片描述
2.2将Spring Application注入到MyWebSocketHandler类中定义的Application中

//将Spring Application注入到MyWebSocketHandler类中定义的Application中。
MyWebSocketHandler.setApplicationContext(run);

在这里插入图片描述

2.3通过getBean方式反射对象

//通过getBean方式反射对象
RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);

在这里插入图片描述

3、成功解决

在这里插入图片描述

;