ssk
ssk

Reputation: 1

springboot websocket do not work @Autowired

In this class @Autowired is work

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private UserDAO userDAO; // is NOT null

    @Autowired
    private IArticleService articleService; // is NOT null

    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new SocketTextHandler(), "/user").addInterceptors(new HttpHandshakeInterceptor());
    }
}

In this class @Autowired is NOT work

public class HttpHandshakeInterceptor implements HandshakeInterceptor {

      @Autowired
      private IArticleService articleService; // is null

      @Autowired
      private UserDAO userDAO; // is null

    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {

    }

Maybe this is something like a channel wss?

Upvotes: 0

Views: 1691

Answers (1)

Hasan Can Saral
Hasan Can Saral

Reputation: 3288

Your HttpHandshakeInterceptor instance is not managed by Spring (i.e. you are creating your instance with new).

You have two options here:

1. Make HttpHandshakeInterceptor Accept Parameters of type UserDAO and IArticleService

public class HttpHandshakeInterceptor implements HandshakeInterceptor {

      private IArticleService articleService;

      private UserDAO userDAO;

      public HttpHandshakeInterceptor(UserDAO userDAO, IArticleService articleService){
          this.userDAO = userDAO;
          this.articleService = articleService;
      }

    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {

    }
  1. Put @Component on top of HttpHandshakeInterceptor

    @Component
    public class HttpHandshakeInterceptor implements HandshakeInterceptor {
    
        @Autowired
        private IArticleService articleService; // is null
    
        @Autowired
        private UserDAO userDAO; // is null
    
        public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
    
        }
    }
    

and use @Autowired in your configuration:

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private HttpHandshakeInterceptor interceptor;

    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new SocketTextHandler(), "/user").addInterceptors(interceptor);
    }
}

You can also achieve what you achieved by @Component annotation with a @Bean definition in one of your @Configuration files.

Additionally, you can also go the route of @Configurable, but from what I see, you don't seem to need it at this point.

Upvotes: 2

Related Questions