1. En la clase de inicio, pase el contexto a la clase que necesita servicio.
@SpringBootApplication
clase pública ChatsystemApplication {
public static void main(String[] args) {
ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(ChatsystemApplication.class, args);
WebSocketServer.setApplicationContext(configurableApplicationContext);
}
2、装入上下文
public class WebSocketServer {
//此处是解决无法注入的关键
private static ApplicationContext applicationContext;
//你要注入的service或者dao
UserService userService;
public static void setApplicationContext (ApplicationContext applicationContext) { WebSocketServer.applicationContext = applicationContext; } 3. Obtenga el servicio a través del método userService = applicationContext.getBean (UserServiceImpl.class); (Tenga en cuenta que la última es la implementación del servicio en getBean)