Search code examples
javaspringspring-mvcwebsocketspring-websocket

how to configure websocket handle using class + spring 4.0.0


can any one help me please for how to configure this web socket bean and handler using class base rather than xml file.

<bean id="websocket" class="co.syntx.example.websocket.handler.WebsocketEndPoint"/>

<websocket:handlers>
    <websocket:mapping path="/websocket" handler="websocket"/>
    <websocket:handshake-interceptors>
    <bean class="co.syntx.example.websocket.HandshakeInterceptor"/>
    </websocket:handshake-interceptors>
</websocket:handlers>

Thanks


Solution

  • Do this in your WebSocketConfig.java

    @Configuration
    @EnableWebSocket
    public class WebSocketConfig implements WebSocketConfigurer {  
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(new WebsocketEndPoint(), "/websocket")
                .addInterceptors(new HandshakeInterceptor());
        }
    }
    

    In the above code, new WebsocketEndPoint() that is WebsocketEndPoint.java will be your websocket handler and new HandshakeInterceptor() that is HandshakeInterceptor.java will be your interceptor.