博主使用的是Springboot自带的WebSocket:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置类如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
修改 Springboot 启动类(HiramGamesWebSocket 换成你的 WebSocket 类):
@SpringBootApplication
@MapperScan("com.hiramgames.dao")
public class HiramgamesApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(HiramgamesApplication.class, args);
HiramGamesWebSocket.setApplicationContext(applicationContext);
}
}
在你的WebSocket类中应该有下面这两个注解("/hiramgames" 换为你的 ws 地址):
@ServerEndpoint(value = "/hiramgames")
@Component
在WebSocket类中增加下面的属性和方法代码:
private static ApplicationContext applicationContext;
public static void setApplicationContext(ApplicationContext context) {
applicationContext = context;
}
在需要使用你想注入的service的地方用如下方式引用:
GameRecordService gameRecordService = applicationContext.getBean(GameRecordService.class);