Java Reference
In-Depth Information
public class MailListener implements MessageListener {
public void onMessage(Message message) {
MapMessage mapMessage = (MapMessage) message;
try {
Mail mail = new Mail();
mail.setMailId(mapMessage.getString("mailId"));
mail.setCountry(mapMessage.getString("country"));
mail.setWeight(mapMessage.getDouble("weight"));
displayMail(mail);
} catch (JMSException e) {
throw JmsUtils.convertJmsAccessException(e);
}
}
private void displayMail(Mail mail) {
System.out.println("Mail #" + mail.getMailId() + " received");
}
}
A message listener must implement the javax.jms.MessageListener interface. When a JMS message
arrives, the onMessage() method will be called with the message as the method argument. In this sample,
you simply display the mail information to the console. Note that when extracting message information
from a MapMessage object, you need to handle the JMS API's JMSException . You can make a call to
JmsUtils.convertJmsAccessException() to convert it into Spring's runtime exception JmsException .
Next, you have to configure this listener in the back office's bean configuration file. Declaring this
listener alone is not enough to listen for JMS messages. You need a message listener container to
monitor JMS messages at a message destination and trigger your message listener on message arrival.
<beans xmlns=" http://www.springframework.org/schema/beans"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="connectionFactory"
class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value=" tcp://localhost:61616" />
</bean>
<bean id="mailListener"
class="com.apress.springenterpriserecipes.post.MailListener" />
<bean
class="org.springframework.jms.listener.SimpleMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destinationName" value="mail.queue" />
<property name ="messageListener" ref="mailListener" />
</bean>
</beans>
Search WWH ::




Custom Search