Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Elements of MDBs

Developers of MDBs must provide the following elements:

  • a message-driven implementation class
  • a JMS message type
  • a deployment descriptor

MessageDrivenBean Interface

An MDB class must implement the javax.ejb.MessageDrivenBean and javax.jms.MessageListener interfaces. A MessageListener interface defines one method, onMessage(Message message); this method is automatically invoked by the container when messages arrive at the destination. MDBs use the onMessage method to consume messages. See the code example below that follows.

public interface javax.jms.MessageListener 
{
    public void onMessage(Message message); 
}

The bean developer is responsible for implementing the ejbCreate() method for the MDB. This method should be used to initialize variables and resources, such as a connection to the database. As part of the MDB instantiation, the container first invokes the newInstance() method followed by the setMessageDrivenContext() method, which passes a message-driven context to the bean instance. The message-driven context provides the container with access to the runtime context—this is valid throughout the life span of the bean instance. The container must execute the ejbCreate() method before the bean instance is transitioned to the ready pool and can consume any messages, as shown in the following example:

public interface javax.ejb.MessageDrivenBean extends EnterpriseBean 
{
    public void ejbRemove() throws EJBException;
    public void setMessageDrivenContext(MessageDrivenContext mctx) throws EJBException; 
} 

The ejbRemove() method is invoked by the container before the container removes the MDB instance from the pool. This method should contain logic to initialize and release any resources allocated in the ejbCreate() method. At the end of the ejbRemove() method execution, the MDB instance is transitioned from memory to the does not exist state.

JMS Message Type

The bean developer must specify the JMS message types and the content of the message within the application. The message producer must create a message from one of the six types—Message, TextMessage, MapMessage, ObjectMessage, StreamMessage, and ByteMessage. Upon receipt of the message, the message consumer must be able to understand the JMS message format, extract the contents of the message, and apply the business logic.

  • + Share This
  • 🔖 Save To Your Account