Reputation: 2952
I'm using Spring 4 and was following the Rossen Stoyanchev's blog post about using websockets in Spring. I was able to get everything working but I'm not sure what the best way to use a custom object mapper when sending application/json
.
I'm injecting a SimpMessageSendingOperations
and calling convertAndSend
. I'm not positive but I'm pretty sure I'm getting a SimpMessagingTemplate
(it implements SimpMessageSendingOperations
) which contains a setMessageConverter
. This method takes a MessageConverter
and there is a MappingJackson2MessageConverter
class but of course it uses it's own internal ObjectMapper
which cannot be redefined.
So what it looks like I have to do is create a custom MessageConverter
and define my custom ObjectMapper
within it so I can pass it to an instance of SimpMessagingTemplate
that I can then inject into my classes.
This seems like it would work, but also more involved than I expected. Am I overlooking something?
Upvotes: 1
Views: 3052
Reputation: 1842
Nowadays you can do it like this:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
// Avoid creating many ObjectMappers which have the same configuration.
converter.setObjectMapper(getMyCustomObjectMapper());
messageConverters.add(converter);
// Don't add default converters.
return false;
}
...
}
Unfortunately ObjectMapper
cannot be given directly to MappingJackson2MessageConverter
's constructor, meaning it will first create a useless ObjectMapper.
Upvotes: 1
Reputation: 2952
Looks like it is possible, but will be made easier in Spring 4.0.1
See - https://jira.springsource.org/browse/SPR-11184
Quote from the bug report above.
In the mean time, with @EnableWebSocketMessageBroker setup you can:
- remove the annotation
- extend WebSocketMessageBrokerConfigurationSupport instead of implementing WebSocketMessageBrokerConfigurer
- override brokerMessageConverter() method and remember to keep @Bean in the overriding method
Upvotes: 3