JmsTemplate Overview

The JmsTemplate is the primary object used for sending messages and receiving messages synchronously (i.e., blocking while waiting to receive messages). There is a JMS template version for JMS 1.1 (JmsTemplate) and a version for JMS 1.0.2 (JmsTemplate102). Since most JMS providers and Java EE application servers now support JMS 1.1, we will be focusing our attention on the JMS 1.1 Spring objects. Using the JmsTemplate significantly reduces the development effort involved in sending and receiving messages. When using the JmsTemplate, you do not need to worry about connecting to the JMS provider, creating a JMS session (e.g., QueueSession), creating a message producer (e.g., QueueSender), or even creating a JMS message (e.g., TextMessage). The JmsTemplate can automatically convert String objects, Byte[] objects, Java objects, and java.util.Map objects into the corresponding JMS message object types. You can also provide your own message converter to provide custom converters for complex messages or other types of messages not supported by the default message converter. The following code example illustrates the simplicity of sending a simple text message using Spring:

public class SimpleJMSSender {

   public static void main(String[] args) {
     try {
       ApplicationContext ctx = 
           new ClassPathXmlApplicationContext("app-context.xml");
       JmsTemplate jmsTemplate = 
           (JmsTemplate)ctx.getBean("jmsTemplate");

       jmsTemplate.convertAndSend("This is easy!");
     }
     ...
   }
}

In this example, the ...

Get Java Message Service, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.