0
# Configuration
1
2
Annotation-based and XML configuration for registering WebSocket handlers and configuring STOMP messaging support.
3
4
## Capabilities
5
6
### WebSocket Configuration
7
8
Basic WebSocket configuration using annotations to register handlers and configure endpoints.
9
10
```java { .api }
11
/**
12
* Annotation to enable WebSocket support in Spring configuration.
13
* Use with @Configuration classes that implement WebSocketConfigurer.
14
*/
15
@Target(ElementType.TYPE)
16
@Retention(RetentionPolicy.RUNTIME)
17
@Documented
18
@Import(DelegatingWebSocketConfiguration.class)
19
@interface EnableWebSocket {
20
}
21
22
/**
23
* Callback interface for customizing WebSocket configuration.
24
* Used with @EnableWebSocket to register WebSocket handlers.
25
*/
26
interface WebSocketConfigurer {
27
/**
28
* Register WebSocket handlers for specific URL patterns.
29
* @param registry the handler registry
30
*/
31
void registerWebSocketHandlers(WebSocketHandlerRegistry registry);
32
}
33
34
/**
35
* Registry for WebSocket handler mappings.
36
* Provides fluent API for handler registration.
37
*/
38
interface WebSocketHandlerRegistry {
39
/**
40
* Add a WebSocket handler for the given URL paths.
41
* @param webSocketHandler the handler instance
42
* @param paths URL patterns to map
43
* @return registration instance for further configuration
44
*/
45
WebSocketHandlerRegistration addHandler(WebSocketHandler webSocketHandler, String... paths);
46
}
47
48
/**
49
* Registration for WebSocket handler with configuration options.
50
* Allows configuring interceptors, handshake handlers, and SockJS support.
51
*/
52
interface WebSocketHandlerRegistration {
53
/**
54
* Add handshake interceptors.
55
* @param interceptors interceptor instances
56
* @return this registration for chaining
57
*/
58
WebSocketHandlerRegistration addInterceptors(HandshakeInterceptor... interceptors);
59
60
/**
61
* Set a custom handshake handler.
62
* @param handshakeHandler the handshake handler
63
* @return this registration for chaining
64
*/
65
WebSocketHandlerRegistration setHandshakeHandler(HandshakeHandler handshakeHandler);
66
67
/**
68
* Enable SockJS fallback support.
69
* @return SockJS registration for further configuration
70
*/
71
SockJsServiceRegistration withSockJS();
72
73
/**
74
* Set allowed origins for CORS support.
75
* @param origins allowed origin patterns
76
* @return this registration for chaining
77
*/
78
WebSocketHandlerRegistration setAllowedOrigins(String... origins);
79
}
80
```
81
82
**Usage Example:**
83
84
```java
85
@Configuration
86
@EnableWebSocket
87
public class WebSocketConfig implements WebSocketConfigurer {
88
89
@Autowired
90
private ChatWebSocketHandler chatHandler;
91
92
@Autowired
93
private EchoWebSocketHandler echoHandler;
94
95
@Override
96
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
97
// Basic handler registration
98
registry.addHandler(chatHandler, "/chat")
99
.setAllowedOrigins("https://example.com", "https://app.example.com");
100
101
// Handler with interceptors and SockJS
102
registry.addHandler(echoHandler, "/echo")
103
.addInterceptors(new HttpSessionHandshakeInterceptor())
104
.withSockJS()
105
.setHeartbeatTime(25000)
106
.setDisconnectDelay(5000);
107
108
// Handler with custom handshake handler
109
registry.addHandler(new AdminWebSocketHandler(), "/admin")
110
.setHandshakeHandler(new CustomHandshakeHandler())
111
.setAllowedOrigins("*");
112
}
113
114
@Bean
115
public ChatWebSocketHandler chatHandler() {
116
return new ChatWebSocketHandler();
117
}
118
119
@Bean
120
public EchoWebSocketHandler echoHandler() {
121
return new EchoWebSocketHandler();
122
}
123
}
124
```
125
126
### WebSocket Message Broker Configuration
127
128
Configuration for STOMP messaging over WebSocket with message broker support.
129
130
```java { .api }
131
/**
132
* Annotation to enable WebSocket message broker support with STOMP.
133
* Use with @Configuration classes that implement WebSocketMessageBrokerConfigurer.
134
*/
135
@Target(ElementType.TYPE)
136
@Retention(RetentionPolicy.RUNTIME)
137
@Documented
138
@Import(DelegatingWebSocketMessageBrokerConfiguration.class)
139
@interface EnableWebSocketMessageBroker {
140
}
141
142
/**
143
* Callback interface for customizing WebSocket message broker configuration.
144
* Used with @EnableWebSocketMessageBroker for STOMP messaging setup.
145
*/
146
interface WebSocketMessageBrokerConfigurer {
147
/**
148
* Register STOMP endpoints for WebSocket connections.
149
* @param registry the STOMP endpoint registry
150
*/
151
default void registerStompEndpoints(StompEndpointRegistry registry) {}
152
153
/**
154
* Configure the message broker for routing messages.
155
* @param registry the message broker registry
156
*/
157
default void configureMessageBroker(MessageBrokerRegistry registry) {}
158
159
/**
160
* Configure WebSocket transport options.
161
* @param registration the transport registration
162
*/
163
default void configureWebSocketTransport(WebSocketTransportRegistration registration) {}
164
165
/**
166
* Configure the client inbound message channel.
167
* @param registration the channel registration
168
*/
169
default void configureClientInboundChannel(ChannelRegistration registration) {}
170
171
/**
172
* Configure the client outbound message channel.
173
* @param registration the channel registration
174
*/
175
default void configureClientOutboundChannel(ChannelRegistration registration) {}
176
177
/**
178
* Configure message converters for STOMP messages.
179
* @param messageConverters list of message converters
180
* @return true if default converters should be added
181
*/
182
default boolean configureMessageConverters(List<MessageConverter> messageConverters) {
183
return true;
184
}
185
}
186
187
/**
188
* Registry for STOMP WebSocket endpoints.
189
* Provides fluent API for endpoint registration.
190
*/
191
interface StompEndpointRegistry {
192
/**
193
* Add a STOMP endpoint at the given URL paths.
194
* @param paths URL patterns for the endpoint
195
* @return endpoint registration for further configuration
196
*/
197
StompWebSocketEndpointRegistration addEndpoint(String... paths);
198
}
199
200
/**
201
* Registration for STOMP WebSocket endpoint configuration.
202
* Allows configuring handshake handlers, interceptors, and SockJS support.
203
*/
204
interface StompWebSocketEndpointRegistration {
205
/**
206
* Set a custom handshake handler.
207
* @param handshakeHandler the handshake handler
208
* @return this registration for chaining
209
*/
210
StompWebSocketEndpointRegistration setHandshakeHandler(HandshakeHandler handshakeHandler);
211
212
/**
213
* Add handshake interceptors.
214
* @param interceptors interceptor instances
215
* @return this registration for chaining
216
*/
217
StompWebSocketEndpointRegistration addInterceptors(HandshakeInterceptor... interceptors);
218
219
/**
220
* Enable SockJS fallback support.
221
* @return SockJS registration for further configuration
222
*/
223
SockJsServiceRegistration withSockJS();
224
225
/**
226
* Set allowed origins for CORS support.
227
* @param origins allowed origin patterns
228
* @return this registration for chaining
229
*/
230
StompWebSocketEndpointRegistration setAllowedOrigins(String... origins);
231
}
232
```
233
234
**Usage Example:**
235
236
```java
237
@Configuration
238
@EnableWebSocketMessageBroker
239
public class WebSocketMessageBrokerConfig implements WebSocketMessageBrokerConfigurer {
240
241
@Override
242
public void registerStompEndpoints(StompEndpointRegistry registry) {
243
// STOMP endpoint with SockJS support
244
registry.addEndpoint("/stomp")
245
.setAllowedOriginPatterns("*")
246
.withSockJS()
247
.setHeartbeatTime(25000);
248
249
// Raw WebSocket endpoint (no SockJS)
250
registry.addEndpoint("/websocket")
251
.setAllowedOriginPatterns("*");
252
253
// Endpoint with custom configuration
254
registry.addEndpoint("/secure-stomp")
255
.setHandshakeHandler(new DefaultHandshakeHandler())
256
.addInterceptors(new HttpSessionHandshakeInterceptor())
257
.setAllowedOrigins("https://trusted-domain.com");
258
}
259
260
@Override
261
public void configureMessageBroker(MessageBrokerRegistry registry) {
262
// Enable simple in-memory broker
263
registry.enableSimpleBroker("/topic", "/queue");
264
265
// Set application destination prefix
266
registry.setApplicationDestinationPrefixes("/app");
267
268
// Optional: Configure external message broker (RabbitMQ, ActiveMQ)
269
// registry.enableStompBrokerRelay("/topic", "/queue")
270
// .setRelayHost("rabbitmq.example.com")
271
// .setRelayPort(61613)
272
// .setClientLogin("guest")
273
// .setClientPasscode("guest");
274
}
275
276
@Override
277
public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
278
// Configure message size limits
279
registration.setMessageSizeLimit(64 * 1024) // 64KB
280
.setSendBufferSizeLimit(512 * 1024) // 512KB
281
.setSendTimeLimit(20000); // 20 seconds
282
}
283
284
@Override
285
public void configureClientInboundChannel(ChannelRegistration registration) {
286
// Configure thread pool for processing inbound messages
287
registration.interceptors(new IpValidationInterceptor())
288
.taskExecutor()
289
.corePoolSize(4)
290
.maxPoolSize(8)
291
.keepAliveSeconds(60);
292
}
293
294
@Override
295
public void configureClientOutboundChannel(ChannelRegistration registration) {
296
// Configure thread pool for sending outbound messages
297
registration.taskExecutor()
298
.corePoolSize(4)
299
.maxPoolSize(8);
300
}
301
302
@Override
303
public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
304
// Add custom message converter for JSON
305
messageConverters.add(new MappingJackson2MessageConverter());
306
307
// Add custom converter for protocol buffers
308
messageConverters.add(new ProtobufMessageConverter());
309
310
return true; // Keep default converters
311
}
312
}
313
```
314
315
### SockJS Configuration
316
317
Configuration options for SockJS fallback transport.
318
319
```java { .api }
320
/**
321
* Configuration and registration for SockJS service.
322
* Provides options for customizing SockJS behavior and transport options.
323
*/
324
class SockJsServiceRegistration {
325
/**
326
* Set the heartbeat time in milliseconds.
327
* @param heartbeatTime heartbeat interval
328
* @return this registration for chaining
329
*/
330
public SockJsServiceRegistration setHeartbeatTime(long heartbeatTime);
331
332
/**
333
* Set the disconnect delay in milliseconds.
334
* @param disconnectDelay delay before closing inactive sessions
335
* @return this registration for chaining
336
*/
337
public SockJsServiceRegistration setDisconnectDelay(long disconnectDelay);
338
339
/**
340
* Set the streaming bytes limit for streaming transports.
341
* @param streamBytesLimit bytes limit before reconnection
342
* @return this registration for chaining
343
*/
344
public SockJsServiceRegistration setStreamBytesLimit(int streamBytesLimit);
345
346
/**
347
* Enable or disable specific transport types.
348
* @param transportType the transport to configure
349
* @param enabled whether the transport should be enabled
350
* @return this registration for chaining
351
*/
352
public SockJsServiceRegistration setTransportTypeEnabled(TransportType transportType, boolean enabled);
353
354
/**
355
* Set allowed origins for SockJS requests.
356
* @param origins allowed origin patterns
357
* @return this registration for chaining
358
*/
359
public SockJsServiceRegistration setAllowedOrigins(String... origins);
360
361
/**
362
* Suppress CORS headers for same-origin requests.
363
* @param suppressCors whether to suppress CORS headers
364
* @return this registration for chaining
365
*/
366
public SockJsServiceRegistration setSuppressCors(boolean suppressCors);
367
}
368
```
369
370
**Usage Example:**
371
372
```java
373
@Configuration
374
@EnableWebSocket
375
public class SockJsConfig implements WebSocketConfigurer {
376
377
@Override
378
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
379
registry.addHandler(new ChatHandler(), "/chat")
380
.withSockJS()
381
.setHeartbeatTime(25000) // 25 second heartbeat
382
.setDisconnectDelay(5000) // 5 second disconnect delay
383
.setStreamBytesLimit(128 * 1024) // 128KB streaming limit
384
.setTransportTypeEnabled(TransportType.WEBSOCKET, true)
385
.setTransportTypeEnabled(TransportType.XHR_POLLING, true)
386
.setTransportTypeEnabled(TransportType.JSONP, false) // Disable JSONP
387
.setAllowedOrigins("*")
388
.setSuppressCors(false);
389
}
390
}
391
```
392
393
### WebSocket Transport Configuration
394
395
Advanced transport configuration options for WebSocket connections.
396
397
```java { .api }
398
/**
399
* Configuration for WebSocket transport options.
400
* Provides settings for message sizes, timeouts, and buffer limits.
401
*/
402
class WebSocketTransportRegistration {
403
/**
404
* Set the maximum message size in bytes.
405
* @param messageSizeLimit max message size
406
* @return this registration for chaining
407
*/
408
public WebSocketTransportRegistration setMessageSizeLimit(int messageSizeLimit);
409
410
/**
411
* Set the send buffer size limit in bytes.
412
* @param sendBufferSizeLimit max send buffer size
413
* @return this registration for chaining
414
*/
415
public WebSocketTransportRegistration setSendBufferSizeLimit(int sendBufferSizeLimit);
416
417
/**
418
* Set the send time limit in milliseconds.
419
* @param sendTimeLimit max time to wait for send operation
420
* @return this registration for chaining
421
*/
422
public WebSocketTransportRegistration setSendTimeLimit(int sendTimeLimit);
423
424
/**
425
* Add handler decorator factories for cross-cutting concerns.
426
* @param factories decorator factory instances
427
* @return this registration for chaining
428
*/
429
public WebSocketTransportRegistration addDecoratorFactory(WebSocketHandlerDecoratorFactory... factories);
430
}
431
```