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="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:jms="http://www.springframework.org/schema/jms"
  xmlns:amq="http://activemq.apache.org/schema/core"
  xsi:schemaLocation="http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core-5.5.0.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

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

  <bean id="jmsTemplate" 
  class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="defaultDestinationName" value="queue1" />

  </bean>


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

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: