JmsTemplate is Spring’s helper for sending and receiving JMS messages through a broker. It handles connection, session, and exception-handling boilerplate so application code can focus on the message. JMS provides a common Java API for brokers; a queue or topic is the destination to which a message is sent. section 9.1 section 9.1.2
Add a Spring Boot JMS starter for Artemis or ActiveMQ, then inject the autoconfigured JmsTemplate into a service. Before sending or receiving, make sure a message broker is available. section 9.1 section 9.1.2
For an order sent to a queue, choose the method that matches how much control you need:
- Use send() with a MessageCreator when you want to construct the JMS Message yourself—for example, with session.createObjectMessage(order). section 9.1.2
- Use convertAndSend("tacocloud.order.queue", order) when you want a configured converter to turn the order into a Message. section 9.1.2
- Add a MessagePostProcessor to convertAndSend() when the converted Message needs customization, such as an X_ORDER_SOURCE property. section 9.1.2
Each sending method can use a configured default destination, a Destination object, or a destination name. For a default queue, set spring.jms.template.default-destination. A MessageConverter controls object conversion; the examples configure MappingJackson2MessageConverter for JSON and a type ID property for identifying the object type. section 9.1.2
@Override
public void sendOrder(TacoOrder order) {
jms.convertAndSend("tacocloud.order.queue", order);
}
This one-line send names the queue and passes the order object; convertAndSend() handles its conversion to a JMS Message. section 9.1.2
To pull an order from a queue, call receive() for a raw Message and convert it separately, or call receiveAndConvert() for a converted object. Both approaches block the calling thread until a message is available. If orders should instead be handed to your code as they arrive, use a message listener with @JmsListener rather than JmsTemplate’s pull methods. section 9.1.3
Listing 9.3 Receiving an already-converted TacoOrder object
package tacos.kitchen.messaging.jms;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import tacos.TacoOrder;
import tacos.kitchen.OrderReceiver;
@Component
public class JmsOrderReceiver implements OrderReceiver {
private JmsTemplate jms;
public JmsOrderReceiver(JmsTemplate jms) {
this.jms = jms;
}
@Override
public TacoOrder receiveOrder() {
return (TacoOrder) jms.receiveAndConvert("tacocloud.order.queue");
}
}
The receiver component injects JmsTemplate and calls receiveAndConvert() on the order queue, returning the result as a TacoOrder. section 9.1.3
