Up to this point, the setup of ActiveMQ server has been completed, and we can proceed to develop a
JMS client using Spring to connect to the server and receive messages.
Implementing a JMS Listener in Spring
To develop a message listener, we need to create a class that implements the javax.jms.MessageListener
interface and implements its onMessage() method. Listing 16-13 shows the class.
Listing 16-13. A JMS Message Listener Class
package com.apress.prospring3.ch16.jms.listener;
import
javax.jms.JMSException;
import
javax.jms.Message;
import
javax.jms.MessageListener;
import
javax.jms.TextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SimpleMessageListener implements MessageListener {
private static final Logger logger =
LoggerFactory.getLogger(SimpleMessageListener.class);
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
logger.info("Message received: " + textMessage.getText());
} catch (JMSException ex) {
logger.error("JMS error", ex);
}
}
}
As shown in Listing 16-13, in the onMessage() method, an instance of the javax.jms.Message
interface will be passed upon message arrival. Within the method, the message was cast to an instance of
the javax.jms.TextMessage interface, and the message body in text was retrieved using the
TextMessage.getText() method. For a list of possible message formats, please refer to JEE's online
documentation (http://docs.oracle.com/javaee/6/api/javax/jms/Message.html).
Having the message listener in place, the next step is to define the Spring ApplicationContext
configuration. Listing 16-14 shows the file (jms-listener-app-context.xml).
Listing 16-14. JMS Message Listener Configuration
<?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"
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home