JMS with spring and activeMq

23 05 2008

JMS is one of most widely used API when async Communication is required. Example could be a simple publish subscribe systems to complex transports in B2B setups.

I have previously worked with JMS using weblogic 9.2.1 and also with IBM MQSeries. Just trying out JMS with activeMq. The motivation to use activeMq is that it is opensource and backed by apache. Spring provides JMS template makes our job easy (Be sure to read about the JMS template and its gotchas). Below are the steps and links to some resources I used. Hope this helps in getting a quick start with activeMq.

1. Download and exract the latest release of activeMq from

2. Change directory to bin and run activemq.bat (Detailed instructions in We have just started a broker process. This process by default runs on port 61616.

3. Open another cmd prompt and run netstat -an|find “61616” to check if activeMq is running

4. We will use Spring JMS template to Connect to activeMq.

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”;

<bean id=”connectionFactory”
<property name=”brokerURL”>

<bean id=”destination” class=”org.apache.activemq.command.ActiveMQQueue”>
<constructor-arg value=”jmsExample” />

<bean id=”jmsTemplate”
<property name=”connectionFactory” ref=”connectionFactory” />



5. Use spring Context to get the JMS template

import javax.jms.JMSException;
import javax.jms.TextMessage;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.jms.core.JmsTemplate;
import org.apache.activemq.command.ActiveMQDestination;

public class SpringInjectRef {

public static void main(String[] args) throws JMSException {

BeanFactory factory = new XmlBeanFactory(new FileSystemResource(

JmsTemplate template = (JmsTemplate) factory.getBean(“jmsTemplate”);
ActiveMQDestination destination = (ActiveMQDestination) factory.getBean(“destination”);

//sending a message
template.convertAndSend(destination, “Hi”);

//recieving a message
Object msg = template.receive(destination);
if (msg instanceof TextMessage) {
try {
System.out.println(((TextMessage) msg).getText());
} catch (JMSException e) {


Note: if you do not want to start a seperate broker then change the Config file as shown below.

<bean id=”connectionFactory”
<property name=”brokerURL”>

This change will create a local Datastore and use it to store the messages. This is will help in cases where you need to start the broker as part of your application.

More about vm transport –

I will add more to this post when time permits.