Java Reference
In-Depth Information
7-4. Creating Message-Driven POJOs in Spring
Problem
When you call the receive() method on a JMS message consumer to receive a message, the calling
thread is blocked until a message is available. During the duration, the thread can do nothing but wait.
This type of message reception is called synchronous reception because your application must wait for
the message to arrive before it can finish its work.
Starting with EJB 2.0, a new kind of EJB component called a message-driven bean (MDB) was
introduced for asynchronous reception of JMS messages. An EJB container can listen for JMS messages
at a message destination and trigger MDBs to react to these messages so that your application no longer
has to wait for messages. In EJB 2.x, besides being a nonabstract, nonfinal public class with a public
constructor and no finalize method, an MDB must implement both the javax.ejb.MessageDrivenBean
and javax.jms.MessageListener interfaces and override all EJB life cycle methods ( ejbCreate and
ejbRemove ). In EJB 3.0, an MDB can be a POJO that implements the MessageListener interface and is
annotated with the @MessageDriven annotation.
Although MDBs can listen for JMS messages, they must be deployed in an EJB container to run. You
may prefer to add the same capability to POJOs so that they can listen for JMS messages without an EJB
container.
Solution
Spring allows beans declared in its IoC container to listen for JMS messages in the same way as
MDBs. Because Spring adds message-listening capabilities to POJOs, they are called message-driven
POJOs (MDPs) .
How It Works
Suppose that you want to add an electronic board to the post office's back office to display mail
information in real time as it arrives from the front desk. As the front desk sends a JMS message along
with mail, the back office subsystem can listen for these messages and display them on the electronic
board. For better system performance, you should apply the asynchronous JMS reception approach to
avoid blocking the thread that receives these JMS messages.
Listening for JMS Messages with Message Listeners
First, you create a message listener to listen for JMS messages. This negates the need for the approach
taken in BackOfficeImpl in previous recipes. For example, the following MailListener listens for JMS
messages that contain mail information:
package com.apress.springenterpriserecipes.post;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import org.springframework.jms.support.JmsUtils;
 
Search WWH ::




Custom Search