原因:
是因为Spring对象的创建都是以单例模式创建的,在启动时只创建一次WebSocket。而WebSocketServer在每个连接请求到来时,都会new一个对象。所以当你启动项目时,你想要注入的对象已经注入进去,但是当用户连接是,新创建的websocket对象没有你要注入的对象,所以会报NullPointerException
解决:
通过static关键字让webSocketService属于WebSocketServer类
1 2 3 4 5 6
| private static WebSocketService webSocketService;
@Autowired public void setKefuService(WebSocketService webSocketService){ WebSocketServer.webSocketService= webSocketService; }
|
使用@ServerEndpoint声明的websocket服务器中自动注入
- 错误方法,这样无法从容器中获取
1 2 3 4 5 6 7
| @ServerEndpoint(value = "/chat/{username}") @Service public class WebSocketServer {
@Resource private RabbitTemplate rabbitTemplate; }
|
- 解决:使用上下文获取
1 2 3 4 5 6 7 8 9 10 11 12 13
| @ServerEndpoint(value = "/chat/{username}") @Service public class WebSocketServer {
private static ApplicationContext context;
public static void setApplicationContext(ApplicationContext applicationContext) { WebSocketServer.context = applicationContext; } }
|
- 在启动类中传入上下文
1 2 3 4 5 6 7 8 9 10
| @SpringBootApplication public class TalkApplication { public static void main(String[] args) { ConfigurableApplicationContext applicationContext = SpringApplication.run(TalkApplication.class, args); WebSocketServer.setApplicationContext(applicationContext); } }
|
- 在使用的地方通过上下文去获取服务
context.getBean();
1 2 3 4 5 6 7
| public void sendSimpleQueue(String message) { String queueName = "talk"; RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); rabbitTemplate.convertAndSend(queueName, message); }
|