Java Reference
In-Depth Information
Sending and Receiving Messages with Spring's JMS Template
Spring offers a JMS template that can significantly simplify your JMS code. To send a JMS message
with this template, you simply call the
send()
method and provide a message destination, as well as a
MessageCreator
object, which creates the JMS message you are going to send. The
MessageCreator
object
is usually implemented as an anonymous inner class.
package com.apress.springenterpriserecipes.post;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
public class FrontDeskImpl implements FrontDesk {
private JmsTemplate jmsTemplate;
private Destination destination;
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void setDestination(Destination destination) {
this.destination = destination;
}
public void sendMail(final Mail mail) {
jmsTemplate.send(destination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
MapMessage message = session.createMapMessage();
message.setString("mailId", mail.getMailId());
message.setString("country", mail.getCountry());
message.setDouble("weight", mail.getWeight());
return message;
}
});
}
}
Note that an inner class can access only arguments or variables of the enclosing method that are
declared as final. The
MessageCreator
interface declares only a
createMessage()
method for you to
implement. In this method, you create and return your JMS message with the JMS session provided.
A JMS template helps you to obtain and release the JMS connection and session, and sends
the JMS message created by your
MessageCreator
object. Moreover, it converts the JMS API's
JMSException
hierarchy into Spring's JMS runtime exception hierarchy, whose base exception class
is
org.springframework.jms.JmsException
. You can catch the
JmsException
thrown from send and
the other send variants and then take action in the catch block if you want.
Search WWH ::
Custom Search