Using Spring message pojo

The Spring Framework has concept of message driven pojo's which are similar to MDB that you can use for receiving messages asynchronously. I wanted to try that out so i changed the sample application that i developed in Using amq namespace for building Spring JMS application for ActiveMQ post. In my sample application i did create a simple MessageListener class that gets called whenever there is a message, you can download the source code for sample application from here First i did create a simple MessageListener POJO class like this

package com.webspherenotes.jms;

public class MessageListener {

  public void handleMessage(String message){
    System.out.println("Inside MessageListener.handleMessage() " 
 + message);
The handleMessage() method of the MessageListener will get called whenever the message is available. Next define the message listener class in the spring configuration like this.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

  <amq:connectionFactory id="connectionFactory"
    brokerURL="tcp://localhost:61616" />

  <bean id="jmsTemplate" 
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="defaultDestinationName" value="queue1" />


  <bean id="messageListener" 
  class="com.webspherenotes.jms.MessageListener" />
  <jms:listener-container connection-factory="connectionFactory">
    <jms:listener destination="queue1" ref="messageListener" 

Now when you run the publisher mvn exec:java -Dexec.mainClass=com.webspherenotes.jms.MessagePublisher it will initialize the spring context and as part of that process it will create MessageListner class and attach it as listener to the destination, so when the message gets published your MessageListner will get called automatically to handle/consume the message.

No comments: