Pergunta

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?

Foi útil?

Solução

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:

  1. remove the annotation
  2. extend WebSocketMessageBrokerConfigurationSupport instead of implementing WebSocketMessageBrokerConfigurer
  3. override brokerMessageConverter() method and remember to keep @Bean in the overriding method

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top