0

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("*");
    }
}
patterson7019
  • 297
  • 1
  • 9
  • Your `McpWebSocketHandler` instance isn't managed by Spring, you are creating an instance yourself. Marking as a duplicate of https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null – M. Deinum Apr 27 '22 at 09:05

0 Answers0