Tomcat + Spring + ActiveMQ

In this tutorial, we are going to learn how to use Queues and Topics as managed resources in Tomcat as client and use Spring to listen and send messages to/from ActiveMQ. We are going to create a war application for listening to queues in ActiveMQ.

Example Scenario:

We have two queues in ActiveMQ – firstQueue and secondQueue. Whenever we send a sentence as message to “firstQueue”, it should be consumed by our client and thereafter, the characters  and their number of occurrences in the sentence should reach “secondQueue” as a message.

Project Artifacts:

1. Technologies used –

a. Eclipse IDE for Java EE developer (Mars)
b. Preinstalled Maven with Eclipse Mars
c. Java 1.8
d. ActiveMQ 5.12.0
e. Spring 4.2.2.RELEASE

2. Eclipse project folder structure:


3. Jars Used

If you are not using Maven, here is the list of jars you would need for this project:


4. Maven Dependencies

file:pom.xml . Paste the below content to pom.xml. It has activemq and spring dependencies.

<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">
    <name>TomcatSpringActiveMQClient Maven Webapp</name>

5. Deployment Descriptor


<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "" >
    <display-name>Archetype Created Web Application</display-name>

6. Tomcat changes for JNDI

Add the following entry to Tomcat context.xml in <TOMCAT_HOME>/config folder as a child of Context root tag . This entry instructs Tomcat to enter these resources in JNDI which would be “looked up” by the application with the same JNDI name. Please note that we have used ActiveMQ pooling connection factory for better performance and scalability.

			<Resource name="jms/activemqConnFact" auth="Container" type="org.apache.activemq.pool.PooledConnectionFactory" description="JMS Connection Factory" factory="org.apache.activemq.jndi.JNDIReferenceFactory" brokerURL="tcp://localhost:61616" brokerName="localhost" maxConnections="10"></Resource>
<Resource name="jms/sendToQueue" auth="Container" type="org.apache.activemq.command.ActiveMQQueue" description="My Sending Queue" factory="org.apache.activemq.jndi.JNDIReferenceFactory" physicalName="secondQueue"></Resource>
<Resource name="jms/receiveFromQueue" auth="Container" type="org.apache.activemq.command.ActiveMQQueue" description="My Receiving Queue" factory="org.apache.activemq.jndi.JNDIReferenceFactory" physicalName="firstQueue"></Resource>

7. Spring Application Context.

file:applicationContext.xml. This is the main spring configuration file for our application to listen to ActiveMQ queues. If you are not using JNDI for some reason, please replace the JNDI lookup spring tags with bean declaration of connection factory and queues.

<beans xmlns="" xmlns:xsi="" xmlns:jms="" xmlns:jee="" xmlns:context="" xsi:schemaLocation="         ">
    <!-- To recognize Autowire annotation in listener class -->
    <!-- Template class for sending messages. -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <constructor-arg ref="activemqConnectionFactory"></constructor-arg>
        <property name="sessionTransacted" value="false"></property>
        <property name="defaultDestination" ref="jmsTemplateDest"></property>
        <property name="deliveryPersistent" value="false"></property>
    <bean id="messageListener" class="com.javanbeyond.MyMessageListenerSender"></bean>
    <!-- Listener class which gets any message that arrives at the queue "FirstQueue" -->
    <jms:listener-container container-type="default" connection-factory="activemqConnectionFactory" acknowledge="auto" destination-resolver="myDestinationResolver">
        <!-- The destination should match the id of JNDI lookup. The Destination Resolver decides how to resolve the destination. In this case, it would look for an id with the destination value in Spring application Context. If no destination resolver is mentioned, the name will be taken as Queue or Topic name of Message provider -->
        <jms:listener destination="jmsReceiveJndi" ref="messageListener" concurrency="3-5"></jms:listener>
    <bean id="myDestinationResolver" class=""></bean>
    <!-- Getting connection factory and destination queues from JNDI.Topics can similarly be obtained, if needed -->
    <jee:jndi-lookup id="activemqConnectionFactory" jndi-name="jms/activemqConnFact" expected-type="javax.jms.ConnectionFactory"></jee:jndi-lookup>
    <jee:jndi-lookup id="jmsTemplateDest" jndi-name="jms/sendToQueue" expected-type="javax.jms.Queue"></jee:jndi-lookup>
    <jee:jndi-lookup id="jmsReceiveJndi" jndi-name="jms/receiveFromQueue" expected-type="javax.jms.Queue"></jee:jndi-lookup>

8. Listener class which can send message as well. This class receives the message from ActiveMQ and send it to “secondQueue” with the help of JmsTemplate. Please note that we could have also used JmsTemplate to receive messages synchronously. But listener classes are better suited for getting messages from Message Providers.


package com.javanbeyond;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

// Listener class that gets message from one queue and send it to other queue
// Here Sending and Receiving of messages happening in the same class.
// In practical circumstances, these operations may be distributed in different classes.
public class MyMessageListenerSender implements MessageListener {

  JmsTemplate jmsTemplate;

  public void onMessage(Message msg) {
    if (msg instanceof TextMessage) {
      final TextMessage text = (TextMessagemsg;
      try {
        System.out.println("Received Message : " + text.getText());
        System.out.println("Sending message to Other Queue");
        jmsTemplate.send(new MessageCreator() {
          public Message createMessage(Session session)
              throws JMSException {
            // Creating Map message. We can create
            // Bytes,Stream,Object,Text message as well
            MapMessage mapMsg = session.createMapMessage();
            Map<Character, Integer> characterMap = calculateLetterNumber(
            for (Entry<Character, Integer> entry : characterMap
                .entrySet()) {
            return mapMsg;
      catch (JMSException e) {

  private Map<Character, Integer> calculateLetterNumber(String sentence) {
    Map<Character, Integer> characterMap = new HashMap<Character, Integer>();
    for (Character c : sentence.toCharArray()) {
      if (characterMap.containsKey(c)) {
        characterMap.put(c, characterMap.get(c1);
      else {
        characterMap.put(c, 1);
    return characterMap;


Example Execution:

  1. Start ActiveMQ and login as admin/admin and click on “Queues” tab.
  2. Start Tomcat and deploy the application. You should see three listeners listening to “firstQueue”.


3. Click on “Send To”  in “Operations” column. Write anything of your choice as the body of the message.


4. Click on “Send”. In eclipse console, you will see the message you typed.

Received Message : This message is listened by Spring...
Sending message to Other Queue

5. Refresh the “Queues” tab in ActiveMQ and click on “secondQueue” and then the first message.

6. You should see each letter of the sentence you typed with their number of occurrences.




Leave a Reply

Back to Top
%d bloggers like this: