【解决方案】需要通过Spring 上下文来获取该对象
-
错误方法,这样无法从容器中获取
会产生空指针异常
-
解决方法,使用上下文获取
第一步:在WebSocketServer中,使用set方法传入上下文
private static ApplicationContext applicationContext;
public static void setApplicationContext(ApplicationContext applicationContext) {
WebSocketServer.applicationContext = applicationContext;
}
第二步:在启动类中传入上下文
//解决springboot和websocket之间使用@autowired注入为空问题 ConfigurableApplicationContext applicationContext = SpringApplication.run(ZaiApplication.class, args); //这里将Spring Application注入到websocket类中定义的Application中。 WebSocketServer.setApplicationContext(applicationContext);
第三步:在使用的地方通过上下文去获取服务
UserService userService = applicationContext.getBean(UserService.class);



