A MessageConverter specifies how to convert between Java objects and JMS messages.
Spring JMS comes with a number of implementations that are ready to use. By default, the SimpleMessageConverter is used by the framework. It is able to handle TextMessages, BytesMessages, MapMessages, and ObjectMessages.
Let’s build an example to show how you can use a message converter with Spring JMS. We start from a previous Spring with JMS example. We will adapt it so that we can send a Person object that gets converted to/from JSON.
Note that Spring JMS ships with a MappingJackson2MessageConverter that converts messages to and from JSON. We will not use it and create our own custom implementation instead.
2. General Project Overview
We will use the following tools/frameworks:
Spring JMS 5.1
Spring Boot 2.1
Our project has the following directory structure:
3. Create a Custom JSON Message Converter
First, we define a simple Person class that contains a name and age. It is a simple POJO with the needed constructors and getters/setters.
Next, create a PersonMessageConverter class that implements the MessageConverter interface.
You need to implement two methods: toMessage() and fromMessage(). These specify how the conversion between the Person object and JMS message is done.
In the toMessage() method we create a TextMessage. As payload, we set the JSON String representation of a Person.
The fromMessage() method converts the JSON String from a JMS message into a Person.
The conversion between a Java object and JSON is done using a JacksonObjectMapper.
You can also set the MessageConverter on the JmsTemplate and MessageListenerContainer using setMessageConverter(). But this means you need to create these Beans as we saw in a previous Spring JMS Example.
To wrap up, make sure to also change the Sender and Receiver so that a Person object is sent/received.
4. Test the JMS Message Converter
To test the message converter, create a Person and send it to the converter.q queue.
Open a command prompt in the root directory of the project. Execute the following Maven command:
The log output shows that the message is converted to/from a JSON representation.
If you would like to run the above code sample you can get the full source code here.
In this tutorial, you learned how to create a custom Spring JMS message converter.