0
# Message Conversion
1
2
Comprehensive message conversion system for automatic translation between Java objects and JMS messages. Spring JMS provides multiple converter implementations supporting JSON, XML, and custom serialization formats with intelligent type handling and configuration options.
3
4
## Capabilities
5
6
### MessageConverter Interface
7
8
Core interface for message conversion between Java objects and JMS messages, enabling seamless integration of POJOs with JMS messaging.
9
10
```java { .api }
11
/**
12
* Strategy interface for converting between Java objects and JMS messages
13
*/
14
public interface MessageConverter {
15
16
/**
17
* Convert a Java object to a JMS message
18
* @param object the object to convert
19
* @param session the JMS session to use for message creation
20
* @return the JMS message
21
* @throws JMSException in case of JMS errors
22
* @throws MessageConversionException in case of conversion errors
23
*/
24
Message toMessage(Object object, Session session) throws JMSException, MessageConversionException;
25
26
/**
27
* Convert a JMS message to a Java object
28
* @param message the JMS message to convert
29
* @return the converted Java object
30
* @throws JMSException in case of JMS errors
31
* @throws MessageConversionException in case of conversion errors
32
*/
33
Object fromMessage(Message message) throws JMSException, MessageConversionException;
34
}
35
36
/**
37
* Extended message converter interface with conversion hint support
38
*/
39
public interface SmartMessageConverter extends MessageConverter {
40
41
/**
42
* Convert a Java object to a JMS message with conversion hint support
43
* @param object the object to convert
44
* @param session the JMS session
45
* @param conversionHint an extra object passed to the MessageConverter for context
46
* @return the JMS message
47
* @throws JMSException in case of JMS errors
48
* @throws MessageConversionException in case of conversion errors
49
*/
50
Message toMessage(Object object, Session session, Object conversionHint)
51
throws JMSException, MessageConversionException;
52
53
/**
54
* Convert a JMS message to a Java object of the specified target class
55
* @param message the JMS message to convert
56
* @param targetClass the target class for conversion
57
* @return the converted Java object
58
* @throws JMSException in case of JMS errors
59
* @throws MessageConversionException in case of conversion errors
60
*/
61
<T> T fromMessage(Message message, Class<T> targetClass) throws JMSException, MessageConversionException;
62
}
63
```
64
65
### SimpleMessageConverter
66
67
Default message converter supporting basic Java types and automatic serialization for complex objects.
68
69
```java { .api }
70
/**
71
* Simple message converter for basic types and Serializable objects
72
*/
73
public class SimpleMessageConverter implements MessageConverter {
74
75
public SimpleMessageConverter();
76
77
// Configuration
78
public void setCreateMessageIdOnSend(boolean createMessageIdOnSend);
79
public void setCreateTimestampOnSend(boolean createTimestampOnSend);
80
81
// Type mapping methods
82
protected Message createMessageForString(String text, Session session) throws JMSException;
83
protected Message createMessageForByteArray(byte[] bytes, Session session) throws JMSException;
84
protected Message createMessageForMap(Map<?, ?> map, Session session) throws JMSException;
85
protected Message createMessageForSerializable(Serializable object, Session session) throws JMSException;
86
87
// Extraction methods
88
protected String extractStringFromMessage(TextMessage message) throws JMSException;
89
protected byte[] extractByteArrayFromMessage(BytesMessage message) throws JMSException;
90
protected Map<?, ?> extractMapFromMessage(MapMessage message) throws JMSException;
91
protected Serializable extractSerializableFromMessage(ObjectMessage message) throws JMSException;
92
}
93
```
94
95
### MappingJackson2MessageConverter
96
97
JSON message converter using Jackson for serializing objects to JSON format, supporting custom ObjectMapper configuration and type handling.
98
99
```java { .api }
100
/**
101
* Message converter using Jackson for JSON serialization
102
*/
103
public class MappingJackson2MessageConverter implements SmartMessageConverter {
104
105
// Constructors
106
public MappingJackson2MessageConverter();
107
108
// ObjectMapper configuration
109
public void setObjectMapper(ObjectMapper objectMapper);
110
public ObjectMapper getObjectMapper();
111
112
// Target type configuration
113
public void setTargetType(MessageType targetType);
114
public MessageType getTargetType();
115
116
// Type mapping configuration
117
public void setTypeIdPropertyName(String typeIdPropertyName);
118
public void setTypeIdMappings(Map<String, Class<?>> typeIdMappings);
119
120
// Encoding configuration
121
public void setEncoding(String encoding);
122
public String getEncoding();
123
124
// Message properties configuration
125
public void setCreateMessageIdOnSend(boolean createMessageIdOnSend);
126
public void setCreateTimestampOnSend(boolean createTimestampOnSend);
127
}
128
129
/**
130
* Enumeration of JMS message types for targeting specific message formats
131
*/
132
public enum MessageType {
133
TEXT,
134
BYTES,
135
MAP,
136
OBJECT
137
}
138
```
139
140
### MarshallingMessageConverter
141
142
Message converter using Spring's marshalling framework for XML serialization, supporting various XML binding technologies.
143
144
```java { .api }
145
/**
146
* Message converter using Spring's marshalling/unmarshalling framework
147
*/
148
public class MarshallingMessageConverter implements MessageConverter {
149
150
// Constructors
151
public MarshallingMessageConverter();
152
public MarshallingMessageConverter(Marshaller marshaller);
153
public MarshallingMessageConverter(Marshaller marshaller, Unmarshaller unmarshaller);
154
155
// Marshaller configuration
156
public void setMarshaller(Marshaller marshaller);
157
public void setUnmarshaller(Unmarshaller unmarshaller);
158
159
// Target type configuration
160
public void setTargetType(MessageType targetType);
161
162
// Message properties configuration
163
public void setCreateMessageIdOnSend(boolean createMessageIdOnSend);
164
public void setCreateTimestampOnSend(boolean createTimestampOnSend);
165
}
166
```
167
168
### MessagingMessageConverter
169
170
Converter for Spring Messaging integration, enabling use of Spring Messaging Message objects with JMS.
171
172
```java { .api }
173
/**
174
* Message converter for Spring Messaging integration
175
*/
176
public class MessagingMessageConverter implements MessageConverter {
177
178
public MessagingMessageConverter();
179
public MessagingMessageConverter(MessageConverter payloadConverter);
180
public MessagingMessageConverter(MessageConverter payloadConverter, MessageBuilderFactory messageBuilderFactory);
181
182
// Configuration
183
public void setPayloadConverter(MessageConverter payloadConverter);
184
public void setMessageBuilderFactory(MessageBuilderFactory messageBuilderFactory);
185
public void setHeaderMapper(JmsHeaderMapper headerMapper);
186
public void setStrictContentTypeMatch(boolean strictContentTypeMatch);
187
188
// Header mapping configuration
189
public void setInboundHeaderNames(String... inboundHeaderNames);
190
public void setOutboundHeaderNames(String... outboundHeaderNames);
191
}
192
193
// Supporting interfaces
194
public interface MessageBuilderFactory {
195
<T> MessageBuilder<T> withPayload(T payload);
196
}
197
198
public interface JmsHeaderMapper {
199
void fromHeaders(MessageHeaders headers, Message target) throws JMSException;
200
MessageHeaders toHeaders(Message source) throws JMSException;
201
}
202
```
203
204
### Message Conversion Exceptions
205
206
Exception hierarchy for message conversion errors with specific error categorization.
207
208
```java { .api }
209
/**
210
* Exception thrown when message conversion fails
211
*/
212
public class MessageConversionException extends JmsException {
213
214
public MessageConversionException(String msg);
215
public MessageConversionException(String msg, Throwable cause);
216
}
217
```
218
219
**Usage Examples:**
220
221
```java
222
import org.springframework.jms.support.converter.*;
223
import com.fasterxml.jackson.databind.ObjectMapper;
224
225
// Configuration with different converters
226
@Configuration
227
public class MessageConversionConfig {
228
229
// Simple converter for basic types
230
@Bean
231
public MessageConverter simpleMessageConverter() {
232
SimpleMessageConverter converter = new SimpleMessageConverter();
233
converter.setCreateMessageIdOnSend(true);
234
converter.setCreateTimestampOnSend(true);
235
return converter;
236
}
237
238
// Jackson JSON converter
239
@Bean
240
public MessageConverter jsonMessageConverter() {
241
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
242
converter.setTargetType(MessageType.TEXT);
243
converter.setTypeIdPropertyName("_type");
244
245
// Custom ObjectMapper configuration
246
ObjectMapper objectMapper = new ObjectMapper();
247
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
248
converter.setObjectMapper(objectMapper);
249
250
return converter;
251
}
252
253
// XML marshalling converter
254
@Bean
255
public MessageConverter xmlMessageConverter() {
256
// Assuming JAXB marshaller
257
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
258
marshaller.setPackagesToScan("com.example.model");
259
260
MarshallingMessageConverter converter = new MarshallingMessageConverter(marshaller);
261
converter.setTargetType(MessageType.TEXT);
262
return converter;
263
}
264
265
// JmsTemplate with custom converter
266
@Bean
267
public JmsTemplate jmsTemplate() {
268
JmsTemplate template = new JmsTemplate(connectionFactory());
269
template.setMessageConverter(jsonMessageConverter());
270
return template;
271
}
272
}
273
274
// Usage in service classes
275
@Service
276
public class ProductService {
277
278
@Autowired
279
private JmsTemplate jmsTemplate;
280
281
// Sending objects - automatically converted to JSON
282
public void publishProduct(Product product) {
283
jmsTemplate.convertAndSend("product.events", product);
284
}
285
286
// Receiving objects - automatically converted from JSON
287
@JmsListener(destination = "product.events")
288
public void handleProductEvent(Product product) {
289
System.out.println("Received product: " + product.getName());
290
}
291
292
// Manual conversion with specific converter
293
public void sendWithCustomConversion() {
294
MessageConverter converter = new MappingJackson2MessageConverter();
295
296
jmsTemplate.send("custom.queue", session -> {
297
Product product = new Product("Test Product");
298
return converter.toMessage(product, session);
299
});
300
}
301
}
302
303
// Custom converter implementation
304
@Component
305
public class CustomProductConverter implements SmartMessageConverter {
306
307
private final ObjectMapper objectMapper = new ObjectMapper();
308
309
@Override
310
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
311
if (object instanceof Product) {
312
try {
313
Product product = (Product) object;
314
String json = objectMapper.writeValueAsString(product);
315
316
TextMessage message = session.createTextMessage(json);
317
message.setStringProperty("productType", product.getType());
318
message.setLongProperty("timestamp", System.currentTimeMillis());
319
320
return message;
321
} catch (Exception e) {
322
throw new MessageConversionException("Failed to convert product", e);
323
}
324
}
325
throw new MessageConversionException("Unsupported object type: " + object.getClass());
326
}
327
328
@Override
329
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
330
if (message instanceof TextMessage) {
331
try {
332
String json = ((TextMessage) message).getText();
333
return objectMapper.readValue(json, Product.class);
334
} catch (Exception e) {
335
throw new MessageConversionException("Failed to convert message to product", e);
336
}
337
}
338
throw new MessageConversionException("Unsupported message type: " + message.getClass());
339
}
340
341
@Override
342
public <T> T fromMessage(Message message, Class<T> targetClass) throws JMSException, MessageConversionException {
343
Object result = fromMessage(message);
344
if (targetClass.isInstance(result)) {
345
return targetClass.cast(result);
346
}
347
throw new MessageConversionException("Cannot convert to target class: " + targetClass);
348
}
349
350
@Override
351
public Message toMessage(Object object, Session session, MessageType targetType)
352
throws JMSException, MessageConversionException {
353
// Implementation for specific target types
354
return toMessage(object, session);
355
}
356
}
357
```