Annotation-based and programmatic configuration for WebSocket endpoints, STOMP messaging, and transport settings. Provides declarative setup through Spring's configuration infrastructure.
Enables WebSocket support in a Spring application context.
/**
* Enable WebSocket request handling in a Spring MVC application.
* To be used on @Configuration classes alongside WebSocketConfigurer.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(DelegatingWebSocketConfiguration.class)
public @interface EnableWebSocket {
}Usage:
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyHandler(), "/ws");
}
}Enables broker-backed STOMP messaging over WebSocket.
/**
* Enable broker-backed messaging over WebSocket using STOMP protocol.
* To be used on @Configuration classes alongside
* WebSocketMessageBrokerConfigurer.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(DelegatingWebSocketMessageBrokerConfiguration.class)
public @interface EnableWebSocketMessageBroker {
}Usage:
@Configuration
@EnableWebSocketMessageBroker
public class StompConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/stomp").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}Defines WebSocket session scope for Spring beans.
/**
* WebSocket session scope annotation. Beans annotated with this scope
* are created once per WebSocket session and destroyed when the session ends.
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Scope(WebSocketScope.SCOPE_WEBSOCKET_SESSION)
@Documented
public @interface WebSocketScope {
/**
* Proxy mode for scoped beans.
*/
ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;
}Callback interface for configuring WebSocket request handling.
/**
* Defines callback methods to configure WebSocket request handling.
* Implemented by @Configuration classes annotated with @EnableWebSocket.
*/
public interface WebSocketConfigurer {
/**
* Register WebSocket handlers mapping them to specific URL paths.
*
* @param registry the registry for WebSocket handlers
*/
void registerWebSocketHandlers(WebSocketHandlerRegistry registry);
}Registry for WebSocket handler mappings.
/**
* Registry for WebSocket handler mappings to URL paths.
*/
public interface WebSocketHandlerRegistry {
/**
* Add a WebSocket handler for the specified URL paths.
*
* @param handler the handler to register
* @param paths the URL paths to map the handler to
* @return a registration object for further configuration
*/
WebSocketHandlerRegistration addHandler(
WebSocketHandler handler,
String... paths);
}Configuration for a WebSocket handler registration.
/**
* Provides configuration options for a WebSocket handler registration.
*/
public interface WebSocketHandlerRegistration {
/**
* Add additional handlers for the same paths.
*/
WebSocketHandlerRegistration addHandler(
WebSocketHandler handler,
String... paths);
/**
* Configure the HandshakeHandler to use.
*/
WebSocketHandlerRegistration setHandshakeHandler(
HandshakeHandler handshakeHandler);
/**
* Add HandshakeInterceptor instances to apply to the handshake.
*/
WebSocketHandlerRegistration addInterceptors(
HandshakeInterceptor... interceptors);
/**
* Set the allowed origins for cross-origin requests.
* Use "*" to allow all origins.
*/
WebSocketHandlerRegistration setAllowedOrigins(String... origins);
/**
* Set allowed origin patterns (supports wildcards).
* Example: "https://*.example.com"
*/
WebSocketHandlerRegistration setAllowedOriginPatterns(
String... originPatterns);
/**
* Enable SockJS fallback options.
*/
SockJsServiceRegistration withSockJS();
}Configuration for SockJS service.
/**
* Provides configuration options for SockJS service registration.
*/
public interface SockJsServiceRegistration {
SockJsServiceRegistration setTaskScheduler(TaskScheduler taskScheduler);
SockJsServiceRegistration setClientLibraryUrl(String clientLibraryUrl);
SockJsServiceRegistration setStreamBytesLimit(int streamBytesLimit);
SockJsServiceRegistration setSessionCookieNeeded(boolean sessionCookieNeeded);
SockJsServiceRegistration setHeartbeatTime(long heartbeatTime);
SockJsServiceRegistration setDisconnectDelay(long disconnectDelay);
SockJsServiceRegistration setHttpMessageCacheSize(int cacheSize);
SockJsServiceRegistration setWebSocketEnabled(boolean webSocketEnabled);
SockJsServiceRegistration setTransportHandlers(TransportHandler... handlers);
SockJsServiceRegistration setTransportHandlerOverrides(
TransportHandler... handlers);
SockJsServiceRegistration setInterceptors(
HandshakeInterceptor... interceptors);
SockJsServiceRegistration setSuppressCors(boolean suppressCors);
SockJsServiceRegistration setMessageCodec(SockJsMessageCodec messageCodec);
}Callback interface for configuring STOMP messaging over WebSocket.
/**
* Defines callback methods to configure message broker options.
* Implemented by @Configuration classes annotated with
* @EnableWebSocketMessageBroker.
*/
public interface WebSocketMessageBrokerConfigurer {
/**
* Register STOMP endpoints mapping each to a specific URL path.
*/
default void registerStompEndpoints(StompEndpointRegistry registry) {}
/**
* Configure WebSocket transport options.
*/
default void configureWebSocketTransport(
WebSocketTransportRegistration registration) {}
/**
* Configure the message channel for inbound messages from clients.
*/
default void configureClientInboundChannel(
ChannelRegistration registration) {}
/**
* Configure the message channel for outbound messages to clients.
*/
default void configureClientOutboundChannel(
ChannelRegistration registration) {}
/**
* Add custom argument resolvers for @MessageMapping methods.
*/
default void addArgumentResolvers(
List<HandlerMethodArgumentResolver> argumentResolvers) {}
/**
* Add custom return value handlers for @MessageMapping methods.
*/
default void addReturnValueHandlers(
List<HandlerMethodReturnValueHandler> returnValueHandlers) {}
/**
* Configure message converters. Return false to add converters
* to the list, true to replace the default converters.
*/
default boolean configureMessageConverters(
List<MessageConverter> messageConverters) {
return true;
}
/**
* Configure message broker options.
*/
default void configureMessageBroker(MessageBrokerRegistry registry) {}
/**
* Lifecycle phase for starting and stopping.
*/
default int getPhase() {
return Integer.MAX_VALUE;
}
}Registry for STOMP endpoint mappings.
/**
* Registry for STOMP over WebSocket endpoints.
*/
public interface StompEndpointRegistry {
/**
* Register a STOMP endpoint at the specified URL paths.
*/
StompWebSocketEndpointRegistration addEndpoint(String... paths);
/**
* Set the order for the HandlerMapping used for STOMP endpoints.
*/
void setOrder(int order);
/**
* Configure a UrlPathHelper for use with STOMP endpoints.
*/
void setUrlPathHelper(UrlPathHelper urlPathHelper);
/**
* Set the error handler for STOMP protocol errors.
*/
void setErrorHandler(StompSubProtocolErrorHandler errorHandler);
/**
* Whether to preserve the order of received messages.
*/
void setPreserveReceiveOrder(boolean preserveReceiveOrder);
}Configuration for a STOMP endpoint registration.
/**
* Provides configuration options for a STOMP endpoint registration.
*/
public interface StompWebSocketEndpointRegistration {
/**
* Enable SockJS fallback options.
*/
SockJsServiceRegistration withSockJS();
/**
* Configure the HandshakeHandler to use.
*/
StompWebSocketEndpointRegistration setHandshakeHandler(
HandshakeHandler handshakeHandler);
/**
* Add HandshakeInterceptor instances.
*/
StompWebSocketEndpointRegistration addInterceptors(
HandshakeInterceptor... interceptors);
/**
* Set allowed origins for cross-origin requests.
*/
StompWebSocketEndpointRegistration setAllowedOrigins(String... origins);
/**
* Set allowed origin patterns (supports wildcards).
*/
StompWebSocketEndpointRegistration setAllowedOriginPatterns(
String... originPatterns);
}Configuration for WebSocket transport.
/**
* Configure WebSocket transport parameters.
*/
public class WebSocketTransportRegistration {
/**
* Set the maximum size for incoming sub-protocol messages.
* Default is 64K.
*/
public WebSocketTransportRegistration setMessageSizeLimit(
int messageSizeLimit);
/**
* Set the maximum time allowed in ms for sending a message.
* Default is 10 seconds.
*/
public WebSocketTransportRegistration setSendTimeLimit(int sendTimeLimit);
/**
* Set the maximum size for the send buffer in bytes.
* Default is 512K.
*/
public WebSocketTransportRegistration setSendBufferSizeLimit(
int sendBufferSizeLimit);
/**
* Set the time limit in ms for the client to send the first message.
* Default is 60 seconds.
*/
public WebSocketTransportRegistration setTimeToFirstMessage(
int timeToFirstMessage);
/**
* Set WebSocketHandler decorator factories to apply.
*/
public WebSocketTransportRegistration setDecoratorFactories(
WebSocketHandlerDecoratorFactory... factories);
/**
* Add a WebSocketHandler decorator factory.
*/
public WebSocketTransportRegistration addDecoratorFactory(
WebSocketHandlerDecoratorFactory factory);
}Central class for aggregating statistics from WebSocket message broker infrastructure. Provides runtime monitoring for WebSocket sessions, STOMP protocol processing, broker relay, and thread pool executors.
/**
* Aggregates information about internal state and counters from key
* infrastructure components of @EnableWebSocketMessageBroker setup.
* By default logs aggregated information every 30 minutes at INFO level.
*
* Declared as Spring bean with name "webSocketMessageBrokerStats"
* and can be exported to JMX for monitoring.
*
* @since 4.1
*/
public class WebSocketMessageBrokerStats implements SmartInitializingSingleton {
/**
* Set the frequency for logging information at INFO level in milliseconds.
* If set to 0 or less, logging is disabled.
* Default is 30 minutes.
*/
public void setLoggingPeriod(long period);
/**
* Return the configured logging period in milliseconds.
*/
public long getLoggingPeriod();
/**
* Get stats about WebSocket sessions including session count and
* WebSocket message processing metrics.
*
* @return session stats, or null if no WebSocket handler configured
* @since 6.2
*/
public SubProtocolWebSocketHandler.Stats getWebSocketSessionStats();
/**
* Get stats about STOMP-related WebSocket message processing including
* connection count, subscriptions, and message rates.
*
* @return STOMP protocol stats, or null if no STOMP handler found
* @since 6.2
*/
public StompSubProtocolHandler.Stats getStompSubProtocolStats();
/**
* Get stats about STOMP broker relay when using a full-featured
* external STOMP broker.
*
* @return broker relay stats, or null if no relay configured
* @since 6.2
*/
public StompBrokerRelayMessageHandler.Stats getStompBrokerRelayStats();
/**
* Get stats about the executor processing incoming messages from
* WebSocket clients. Returns thread pool information including
* pool size, active threads, queued tasks, and completed tasks.
*/
public String getClientInboundExecutorStatsInfo();
/**
* Get stats about the executor processing outgoing messages to
* WebSocket clients.
*/
public String getClientOutboundExecutorStatsInfo();
/**
* Get stats about the SockJS task scheduler including thread pool metrics.
*/
public String getSockJsTaskSchedulerStatsInfo();
}Base class providing configuration support for WebSocket request handling. This class is typically not used directly but is imported via @EnableWebSocket and extended by DelegatingWebSocketConfiguration.
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.web.servlet.HandlerMapping;
/**
* Configuration support for WebSocket request handling.
* Provides the bean definitions for WebSocket infrastructure components.
*
* @author Rossen Stoyanchev
* @author Sebastien Deleuze
* @since 4.0
*/
public class WebSocketConfigurationSupport {
/**
* Create the HandlerMapping that maps WebSocket handshake requests
* to WebSocketHandler instances.
*
* @param schedulerContainer container for the default SockJS TaskScheduler
* @return the configured HandlerMapping
*/
@Bean
public HandlerMapping webSocketHandlerMapping(
@Qualifier("defaultSockJsSchedulerContainer")
DefaultSockJsSchedulerContainer schedulerContainer);
/**
* Override to register WebSocket handlers.
* This method is called by the framework during initialization.
*
* @param registry the WebSocketHandlerRegistry to use
*/
protected void registerWebSocketHandlers(WebSocketHandlerRegistry registry);
/**
* Create a container for the default SockJS TaskScheduler.
* The scheduler is created only if SockJS is enabled and no custom
* scheduler was provided.
*
* @return the scheduler container
*/
@Bean
DefaultSockJsSchedulerContainer defaultSockJsSchedulerContainer();
}Usage Notes:
Implementation of WebSocketConfigurationSupport that detects and delegates to all WebSocketConfigurer beans in the application context. This is the class imported by @EnableWebSocket.
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
/**
* A variation of WebSocketConfigurationSupport that detects implementations of
* WebSocketConfigurer in Spring configuration and invokes them in order to
* configure WebSocket request handling.
*
* @author Rossen Stoyanchev
* @author Sebastien Deleuze
* @since 4.0
*/
@Configuration(proxyBeanMethods = false)
public class DelegatingWebSocketConfiguration extends WebSocketConfigurationSupport {
/**
* Autowired to collect all WebSocketConfigurer beans from the
* application context. Can be empty if no configurers are provided.
*
* @param configurers list of WebSocketConfigurer beans
*/
@Autowired(required = false)
public void setConfigurers(List<WebSocketConfigurer> configurers);
/**
* Delegates to all detected WebSocketConfigurer instances to register
* WebSocket handlers.
*
* @param registry the registry for WebSocket handlers
*/
@Override
protected void registerWebSocketHandlers(WebSocketHandlerRegistry registry);
}How it Works:
Example:
@Configuration
@EnableWebSocket // Imports DelegatingWebSocketConfiguration
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyHandler(), "/ws");
}
}Base class extending AbstractMessageBrokerConfiguration that adds configuration for receiving and responding to STOMP messages from WebSocket clients. Provides the core bean definitions for message broker infrastructure.
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.SimpUserRegistry;
import org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler;
import org.springframework.messaging.simp.broker.AbstractBrokerMessageHandler;
import org.springframework.messaging.support.AbstractSubscribableChannel;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.WebSocketMessageBrokerStats;
/**
* Extends AbstractMessageBrokerConfiguration and adds configuration for
* receiving and responding to STOMP messages from WebSocket clients.
*
* Typically used in conjunction with @EnableWebSocketMessageBroker but can
* also be extended directly.
*
* @author Rossen Stoyanchev
* @author Artem Bilan
* @author Sebastien Deleuze
* @author Juergen Hoeller
* @since 4.0
*/
public abstract class WebSocketMessageBrokerConfigurationSupport
extends AbstractMessageBrokerConfiguration {
/**
* Scope identifier for WebSocket scope: "websocket".
* @since 7.0
*/
public static final String SCOPE_WEBSOCKET = "websocket";
/**
* Create the HandlerMapping for STOMP endpoints.
* Maps STOMP endpoint URLs to WebSocket handlers.
*
* @param subProtocolWebSocketHandler the WebSocket handler for sub-protocols
* @param messageBrokerTaskScheduler the task scheduler for message broker
* @param clientInboundChannel the channel for inbound client messages
* @return the configured STOMP endpoint HandlerMapping
*/
@Bean
public HandlerMapping stompWebSocketHandlerMapping(
WebSocketHandler subProtocolWebSocketHandler,
TaskScheduler messageBrokerTaskScheduler,
AbstractSubscribableChannel clientInboundChannel);
/**
* Create the WebSocket handler that delegates to STOMP sub-protocol handlers.
*
* @param clientInboundChannel channel for messages from clients
* @param clientOutboundChannel channel for messages to clients
* @return the SubProtocolWebSocketHandler
*/
@Bean
public WebSocketHandler subProtocolWebSocketHandler(
AbstractSubscribableChannel clientInboundChannel,
AbstractSubscribableChannel clientOutboundChannel);
/**
* Register STOMP endpoints. Override this method to configure endpoints.
*
* @param registry the STOMP endpoint registry
*/
protected abstract void registerStompEndpoints(StompEndpointRegistry registry);
/**
* Configure WebSocket transport options. Override to customize.
*
* @param registry the WebSocket transport registration
*/
protected void configureWebSocketTransport(
WebSocketTransportRegistration registry);
/**
* Create the custom scope configurer for WebSocket session scope.
*
* @return the scope configurer
*/
@Bean
public static CustomScopeConfigurer webSocketScopeConfigurer();
/**
* Create the stats bean for monitoring WebSocket message broker infrastructure.
*
* @param stompBrokerRelayMessageHandler optional broker relay handler
* @param subProtocolWebSocketHandler the WebSocket handler
* @param inboundExecutor executor for inbound messages
* @param outboundExecutor executor for outbound messages
* @param scheduler task scheduler for broker operations
* @return the WebSocketMessageBrokerStats bean
*/
@Bean
public WebSocketMessageBrokerStats webSocketMessageBrokerStats(
AbstractBrokerMessageHandler stompBrokerRelayMessageHandler,
WebSocketHandler subProtocolWebSocketHandler,
TaskExecutor inboundExecutor,
TaskExecutor outboundExecutor,
TaskScheduler scheduler);
/**
* Create the annotation method message handler for @MessageMapping methods.
*
* @param clientInboundChannel channel for inbound messages
* @param clientOutboundChannel channel for outbound messages
* @param brokerMessagingTemplate template for sending to message broker
* @return the configured message handler
*/
@Override
protected SimpAnnotationMethodMessageHandler createAnnotationMethodMessageHandler(
AbstractSubscribableChannel clientInboundChannel,
AbstractSubscribableChannel clientOutboundChannel,
SimpMessagingTemplate brokerMessagingTemplate);
/**
* Create the local user registry for tracking user sessions.
*
* @param order optional order for the user registry
* @return the SimpUserRegistry
*/
@Override
protected SimpUserRegistry createLocalUserRegistry(Integer order);
/**
* Decorate the WebSocket handler with decorator factories.
*
* @param handler the handler to decorate
* @return the decorated handler
*/
protected WebSocketHandler decorateWebSocketHandler(WebSocketHandler handler);
}Key Responsibilities:
Implementation of WebSocketMessageBrokerConfigurationSupport that detects and delegates to all WebSocketMessageBrokerConfigurer beans. This is the class imported by @EnableWebSocketMessageBroker.
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver;
import org.springframework.messaging.handler.invocation.HandlerMethodReturnValueHandler;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
/**
* A WebSocketMessageBrokerConfigurationSupport extension that detects
* beans of type WebSocketMessageBrokerConfigurer and delegates to all
* of them allowing callback style customization of the configuration provided
* in WebSocketMessageBrokerConfigurationSupport.
*
* This class is typically imported via @EnableWebSocketMessageBroker.
*
* @author Rossen Stoyanchev
* @author Sebastien Deleuze
* @since 4.0
*/
@Configuration(proxyBeanMethods = false)
public class DelegatingWebSocketMessageBrokerConfiguration
extends WebSocketMessageBrokerConfigurationSupport {
/**
* Autowired to collect all WebSocketMessageBrokerConfigurer beans from
* the application context. Can be empty if no configurers are provided.
*
* @param configurers list of WebSocketMessageBrokerConfigurer beans
*/
@Autowired(required = false)
public void setConfigurers(List<WebSocketMessageBrokerConfigurer> configurers);
/**
* Delegates to all detected configurers to register STOMP endpoints.
*
* @param registry the STOMP endpoint registry
*/
@Override
protected void registerStompEndpoints(StompEndpointRegistry registry);
/**
* Delegates to all detected configurers to configure WebSocket transport.
*
* @param registration the transport registration
*/
@Override
protected void configureWebSocketTransport(
WebSocketTransportRegistration registration);
/**
* Delegates to all detected configurers to configure client inbound channel.
*
* @param registration the channel registration
*/
@Override
protected void configureClientInboundChannel(ChannelRegistration registration);
/**
* Delegates to all detected configurers to configure client outbound channel.
*
* @param registration the channel registration
*/
@Override
protected void configureClientOutboundChannel(ChannelRegistration registration);
/**
* Delegates to all detected configurers to add custom argument resolvers.
*
* @param argumentResolvers the list to add resolvers to
*/
@Override
protected void addArgumentResolvers(
List<HandlerMethodArgumentResolver> argumentResolvers);
/**
* Delegates to all detected configurers to add custom return value handlers.
*
* @param returnValueHandlers the list to add handlers to
*/
@Override
protected void addReturnValueHandlers(
List<HandlerMethodReturnValueHandler> returnValueHandlers);
/**
* Delegates to all detected configurers to configure message converters.
*
* @param messageConverters the list of message converters
* @return true to register default converters, false otherwise
*/
@Override
protected boolean configureMessageConverters(
List<MessageConverter> messageConverters);
/**
* Delegates to all detected configurers to configure message broker.
*
* @param registry the message broker registry
*/
@Override
protected void configureMessageBroker(MessageBrokerRegistry registry);
/**
* Get the lifecycle phase from the first configurer that provides one.
*
* @return the lifecycle phase
*/
@Override
protected int initPhase();
}How it Works:
Example:
@Configuration
@EnableWebSocketMessageBroker // Imports DelegatingWebSocketMessageBrokerConfiguration
public class StompConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/stomp").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}Servlet-specific implementation of WebSocketHandlerRegistry that creates Spring MVC handler mappings for WebSocket handshake requests.
import java.util.List;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.web.servlet.handler.AbstractHandlerMapping;
import org.springframework.web.socket.WebSocketHandler;
/**
* WebSocketHandlerRegistry with Spring MVC handler mappings for the
* handshake requests.
*
* @author Rossen Stoyanchev
* @since 4.0
*/
public class ServletWebSocketHandlerRegistry implements WebSocketHandlerRegistry {
/**
* Default constructor.
*/
public ServletWebSocketHandlerRegistry();
/**
* Add a WebSocket handler for the specified URL paths.
*
* @param handler the WebSocket handler
* @param paths the URL paths to map
* @return a registration for further configuration
*/
@Override
public WebSocketHandlerRegistration addHandler(
WebSocketHandler handler,
String... paths);
/**
* Set the order for the resulting HandlerMapping relative to
* other handler mappings configured in Spring MVC.
* Default is 1.
*
* @param order the order value
*/
public void setOrder(int order);
/**
* Get the configured order.
*
* @return the order value
*/
public int getOrder();
/**
* Whether there are any endpoint SockJS registrations without a TaskScheduler.
* This method should be invoked just before getHandlerMapping() to
* allow for registrations to be made first.
*
* @return true if a TaskScheduler is required
*/
protected boolean requiresTaskScheduler();
/**
* Provide the TaskScheduler to use for SockJS endpoints for which a task
* scheduler has not been explicitly registered. This method must be called
* prior to getHandlerMapping().
*
* @param scheduler the TaskScheduler to use
*/
protected void setTaskScheduler(TaskScheduler scheduler);
/**
* Return the AbstractHandlerMapping with all registered handlers.
*
* @return the configured handler mapping
*/
public AbstractHandlerMapping getHandlerMapping();
}Usage Notes:
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/myHandler")
.setAllowedOrigins("*");
}
@Bean
public WebSocketHandler myHandler() {
return new MyWebSocketHandler();
}
}@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/ws")
.setHandshakeHandler(customHandshakeHandler())
.addInterceptors(new HttpSessionHandshakeInterceptor())
.setAllowedOriginPatterns("https://*.example.com");
}
@Bean
public HandshakeHandler customHandshakeHandler() {
return new DefaultHandshakeHandler() {
@Override
protected Principal determineUser(
ServerHttpRequest request,
WebSocketHandler wsHandler,
Map<String, Object> attributes) {
// Extract user from request
return extractUserPrincipal(request);
}
};
}
}@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/ws")
.withSockJS()
.setHeartbeatTime(25000)
.setDisconnectDelay(5000)
.setClientLibraryUrl("https://cdn.example.com/sockjs.min.js");
}
}@Configuration
@EnableWebSocketMessageBroker
public class StompConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// WebSocket endpoint
registry.addEndpoint("/ws");
// SockJS fallback endpoint
registry.addEndpoint("/sockjs").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
// Enable simple in-memory broker
registry.enableSimpleBroker("/topic", "/queue");
// Application destination prefix
registry.setApplicationDestinationPrefixes("/app");
// User destination prefix
registry.setUserDestinationPrefix("/user");
}
}@Configuration
@EnableWebSocketMessageBroker
public class AdvancedStompConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/stomp")
.setHandshakeHandler(customHandshakeHandler())
.addInterceptors(new CustomHandshakeInterceptor())
.setAllowedOrigins("*")
.withSockJS()
.setWebSocketEnabled(true)
.setHeartbeatTime(20000);
registry.setErrorHandler(new CustomStompErrorHandler());
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
// External message broker (RabbitMQ, ActiveMQ, etc.)
registry.enableStompBrokerRelay("/topic", "/queue")
.setRelayHost("localhost")
.setRelayPort(61613)
.setClientLogin("guest")
.setClientPasscode("guest");
registry.setApplicationDestinationPrefixes("/app");
}
@Override
public void configureWebSocketTransport(
WebSocketTransportRegistration registration) {
registration
.setMessageSizeLimit(128 * 1024) // 128KB
.setSendTimeLimit(20 * 1000) // 20 seconds
.setSendBufferSizeLimit(1024 * 1024) // 1MB
.setTimeToFirstMessage(30 * 1000); // 30 seconds
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new CustomChannelInterceptor());
registration.taskExecutor()
.corePoolSize(4)
.maxPoolSize(8)
.queueCapacity(100);
}
@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.taskExecutor()
.corePoolSize(4)
.maxPoolSize(8);
}
}@Component
@WebSocketScope
public class WebSocketScopedBean {
// Bean instance per WebSocket session
private String sessionData;
public void setSessionData(String data) {
this.sessionData = data;
}
public String getSessionData() {
return sessionData;
}
}
@Controller
public class WebSocketController {
private final WebSocketScopedBean sessionBean;
public WebSocketController(WebSocketScopedBean sessionBean) {
this.sessionBean = sessionBean;
}
@MessageMapping("/data")
public void handleData(String data) {
// Each session has its own bean instance
sessionBean.setSessionData(data);
}
}