import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import TestWebSocketController; import TestHandShakeInterceptor; @Configuration @EnableWebMvc @EnableWebSocket public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer { @Autowired private TestWebSocketController testWebSocketController; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(TestWebSocketController, "/testWebSocket") .addInterceptors(new TestHandShakeInterceptor()).setAllowedOrigins("*"); } }
1.3 补充说明
(1)在WebSocket实现过程中,尤其是通过“@ServerEndpoint”实现的时候,可能会出现注入失败的问题,即注入的Bean为null的问题。可以通过手动注入的方式来解决,需要改造实现类和SpringBoot启动类,如下:
@ServerEndpoint("testWebsocket") @RestController public class WebSocketController { private TestService testService; private static ApplicationContext applicationContext; @OnOpen public void onOpen(Session session) { testService = applicationContext.getBean(TestService.class); } @OnClose public void onClose() {} @OnMessage public void onMessage(String message, Session session) {} @OnError public void onError(Session session, Throwable error) {} public static void setApplicationContext(ApplicationContext applicationContext) { WebSocketController.applicationContext = applicationContext; } }
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import WebSocketController; @SpringBootApplication public class Application { public static void main(String[] args) { // SpringApplication.run(Application.class, args); SpringApplication springApplication = new SpringApplication(Application.class); ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args); WebSocketController.setApplicationContext(configurableApplicationContext); // 解决WebSocket不能注入的问题 } }
2. 客户端的实现,我尝试了html和java WebSocketClient两种方式
2.1 html实现