Simple Spring JMS

David Winterfeldt


This is a very simple example using a Spring JMS Template to send messages and also having a JMS listener process the messages sent. An embedded ActiveMQ instance is used as the broker.

1. Producer Configuration

Spring Configuration

The Spring configuration shows a context:component-scan that picks up the JMS producer and listener. Following this the Spring custom namespace for Apache's ActiveMQ is used to create an embedded JMS broker. A queue is configured for 'org.springbyexample.jms.test'. Then a JMS connection factory is made for the JmsTemplate to use. The template will be used by the producer to send messages.

Excerpt from JmsMessageListenerTest-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    <context:component-scan base-package="org.springbyexample.jms" />
    <!--  Embedded ActiveMQ Broker -->
    <amq:broker id="broker" useJmx="false" persistent="false">
            <amq:transportConnector uri="tcp://localhost:0" />

    <!--  ActiveMQ Destination  -->
    <amq:queue id="destination" physicalName="org.springbyexample.jms.test" />

    <!-- JMS ConnectionFactory to use, configuring the embedded broker using XML -->
    <amq:connectionFactory id="jmsFactory" brokerURL="vm://localhost" />

    <!-- JMS Producer Configuration -->
    <bean id="jmsProducerConnectionFactory" 
          p:targetConnectionFactory-ref="jmsFactory" />

    <bean id="jmsProducerTemplate" class="org.springframework.jms.core.JmsTemplate"
          p:defaultDestination-ref="destination" />


Code Example

The producer uses @PostConstruct to indicate that generateMessages() is an initialization method. It uses the JmsTemplate to send text messages and also sets an int property for the message count.

Example 1. JmsMessageProducer

public class JmsMessageProducer {

    private static final Logger logger = LoggerFactory.getLogger(JmsMessageProducer.class);

    protected static final String MESSAGE_COUNT = "messageCount";

    private JmsTemplate template = null;
    private int messageCount = 100;

     * Generates JMS messages
    public void generateMessages() throws JMSException {
        for (int i = 0; i < messageCount; i++) {
            final int index = i;
            final String text = "Message number is " + i + ".";

            template.send(new MessageCreator() {
                public Message createMessage(Session session) throws JMSException {
                    TextMessage message = session.createTextMessage(text);
                    message.setIntProperty(MESSAGE_COUNT, index);
          "Sending message: " + text);
                    return message;