A MessageConverter turns an application object into a message for sending and turns a received message back into an object. With JMS, JmsTemplate.convertAndSend() uses a converter behind the scenes, so you can send an order without creating a JMS Message yourself. JmsTemplate.receiveAndConvert() performs the reverse step. section 9.1.2 section 9.1.3
Send an order without building a Message
jms.convertAndSend("tacocloud.order.queue", order); The order is converted before it is sent. Unlike jms.send(), this call does not require a MessageCreator. section 9.1.2
The JMS MessageConverter interface has two methods: toMessage(Object, Session) and fromMessage(Message). Spring’s default SimpleMessageConverter supports several message forms, but sending a domain object as an ObjectMessage requires it to implement Serializable. A Jackson-based converter is an alternative when you want JSON instead. section 9.1.2
Table 9.3 Spring message converters for common conversion tasks (all in the org.springframework.jms.support.converter package) (view table figure)
Compare the supplied JMS converters by the data they handle, including JSON, XML, strings, byte arrays, maps, and serializable objects. section 9.1.2
Configure JSON conversion for JMS
@Bean public MappingJackson2MessageConverter messageConverter() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); converter.setTypeIdPropertyName("_typeId"); return converter; } Declaring the converter as a bean replaces the default. The type-ID property helps a receiver choose the type to reconstruct; type-ID mappings can also associate a short identifier such as "order" with TacoOrder. section 9.1.2
When receiving with JMS, use receiveAndConvert() if you need only the order object. Use receive() and call the converter’s fromMessage() yourself if you also need to inspect the raw message’s properties or headers. section 9.1.3
RabbitTemplate has a corresponding conversion workflow, but its MessageConverter is in the Spring AMQP package rather than the JMS package. It can convert an order for send(), while convertAndSend() handles that step automatically; receiveAndConvert() converts a queued message on receipt. For RabbitMQ JSON messages, declare a Jackson2JsonMessageConverter bean. section 9.2.2 section 9.2.3
