开始:在webSocket中是不能直接使用autowired注入SpringBean的。
解决方法:
1.在webSocket类中加入以下代码。
/**
* 解决无法注入
*/
private static ApplicationContext applicationContext;
//你要注入的bean
private StudentRepository studentRepository;
//在主入口中注入applicationContext
public static void setApplicationContext(ApplicationContext applicationContext){
UserSocket.applicationContext = applicationContext;
}
2.在springboot 启动类的main方法修改成这样。
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(HkTeacherManagerApplication.class); //这里填你的Class名字
ConfigurableApplicationContext run = springApplication.run(args);
//注入application
UserSocket.setApplicationContext(run);
}
3.在需要使用的地方获取SpringBean
//获取SessionId
studentRepository = (StudentRepository) applicationContext.getBean("studentRepository");
List<Student> all = studentRepository.findAll();