I have a websocket handler McpWebSocketHandler , and I was expecting to be able to access the ApplicationContext, and a service I defined, via the @Autowired annotation. However they are null when McpWebSocketHandler.handleMessage() gets called. The appContext and gameUnitService are both available in my WebSocketConfig. Perhaps I should just be passing the context and service into my McpWebSocketHandler() constructor?
public class McpWebSocketHandler extends AbstractWebSocketHandler {
@Autowired private ApplicationContext appContext;
@Autowired private GameUnitService gameUnitService;
@Override
public void handleMessage(WebSocketSession session,WebSocketMessage<?> message) throws Exception {
//appContext and gameUnitService are both null
}
My service is defined with a @Serivce annotation:
@Service
public class GameUnitService { ... }
The application context and service are properly injected from a rest controller:
@RestController
public class MCPController {
@Autowired private GameUnitService gameUnitService;
@Autowired private ApplicationContext appContext;
@GetMapping("/ping")
public Object ping(HttpServletRequest request) {
assert(appContext != null); //appContext is not null
return new Response(true, ErrorCode.OK, "pong");
}
My WebSocketConfig which properly injects appContext and gameUnitService :
@Configuration
@EnableWebSocket
public class McpWebSocketConfig implements WebSocketConfigurer {
@Autowired private GameUnitService gameUnitService;
@Autowired private ApplicationContext appContext;
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setMaxBinaryMessageBufferSize(1024000);
return container;
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new McpWebSocketHandler(), "/socket").setAllowedOrigins("*");
registry.addHandler(new McpWebSocketHandler(), "/").setAllowedOrigins("*");
}
}