title: ApplicationContext and services from WebSocketHandler in a spring boot app
body: <p>I have a websocket handler <code>McpWebSocketHandler </code>, and I was expecting to be able to access the ApplicationContext, and a service I defined, via the <code>@Autowired</code> annotation. However they are null when <code>McpWebSocketHandler.handleMessage()</code> gets called. The appContext and gameUnitService <em>are</em> both available in my <code>WebSocketConfig</code>. Perhaps I should just be passing the context and service into my <code>McpWebSocketHandler()</code> constructor?</p>
  <pre><code>public class McpWebSocketHandler extends AbstractWebSocketHandler {
      @Autowired private ApplicationContext appContext;
      @Autowired private GameUnitService gameUnitService;
  
      @Override
      public void handleMessage(WebSocketSession session,WebSocketMessage&lt;?&gt; message) throws Exception {
        //appContext and gameUnitService are both null
      }
  
  </code></pre>
  <p>My service is defined with a @Serivce annotation:</p>
  <pre><code>@Service
  public class GameUnitService { ... }
  </code></pre>
  <p>The application context and service are properly injected from a rest controller:</p>
  <pre><code>@RestController
  public class MCPController {
      @Autowired private GameUnitService gameUnitService;
      @Autowired private ApplicationContext appContext;
  
      @GetMapping(&quot;/ping&quot;)
      public Object ping(HttpServletRequest request) {
          assert(appContext != null);  //appContext is not null
          return new Response(true, ErrorCode.OK, &quot;pong&quot;);
      }
  </code></pre>
  <p>My WebSocketConfig which properly injects appContext and gameUnitService :</p>
  <pre><code>@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(), &quot;/socket&quot;).setAllowedOrigins(&quot;*&quot;);
          registry.addHandler(new McpWebSocketHandler(), &quot;/&quot;).setAllowedOrigins(&quot;*&quot;);
      }
  }
  </code></pre>