springboot websocket不起作用@Autowired

时间:2018-09-25 11:04:48

标签: spring-boot websocket autowired

在此类中@Autowired是可行的

 $( function() {
    $('tr').click( function() {
    $(this).toggleClass("green-cell");
    if ($(this).hasClass("green-cell")) {
      count += 1;
    } else {
      count -= 1;
    }
    button.innerHTML =   count;
    } );
    } );

在此类中,@ Autowired不起作用

@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());
    }
}

也许这就像频道的wss一样?

1 个答案:

答案 0 :(得分:0)

您的HttpHandshakeInterceptor实例不受Spring的管理(即您正在使用new创建实例)。

您在这里有两个选择:

1。使HttpHandshakeInterceptor接受类型为UserDAOIArticleService的参数

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. @Component放在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) {
    
        }
    }
    

并在配置中使用@Autowired

@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);
    }
}

您还可以在@Component个文件之一中使用@Bean定义的@Configuration注释来实现您的目标。

此外,您也可以沿@Configurable的路线行驶,但是据我所知,此时您似乎不需要它。