Show TOC

Developing the Message-Driven BeanLocate this document in the navigation structure

Procedure

In this step you create a message driven bean (MDB) that receives messages asynchronously. This enterprise bean has one obligatory method called onMessage() , which comes from the MessageListener interface.

  1. In the context menu of the EJB project, choose Start of the navigation path New Next navigation step Other Next navigation step EJB Next navigation step Message-Driven Bean (EJB 3.x) End of the navigation path, then choose Next .

  2. In the Class name field, specify the name of the MDB, such as MDBBean , and name the Java package , such as com.sap.jms.test.MDBEjbBean .

  3. Select the JMS checkbox, and select Queue in the Destination type dropdown list. The JMS destination type must correspond to the resource name in the jms-resources.xml . Choose Next .

  4. In the Bean name field, enter the MyVeryNewQueue . This is the destination on which your MDB listens for messages.

  5. Choose Finish .

Implementation of the Methods

You created MDBBean.java in the test package in the ejbModule . Now you have to implement this Java file. Here is an example:

Sample Code
                  package com.sap.jms.test.MDBEjbBean;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * 
 * A Message-Driven Bean processing TextMessages sent to MyVeryNewQueue.
 * 
 */

@MessageDriven(mappedName = "MyVeryNewQueue", activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") })

public class MDBBean implements MessageListener {

   /**
         * 
         * Receives a single JMSMessage from the specified Queue.
         * 
         * 
         * 
         * @param msg
         * 
         * the message received from MyVeryNewQueue
         * 
         */

   public void onMessage(Message msg) {
      try {
         // expecting only TextMessages
         if (msg instanceof TextMessage) {
            TextMessage textMsg = (TextMessage) msg;
            System.out.println("MDBBean: Message received: "
                  + textMsg.getText());
         } else {
            System.out.println("MDBBean: Message of wrong type: "
                  + msg.getClass().getName());
         }
      } catch (JMSException jmsexc) {
         System.out.println("MDBBean: Message processing failed. " + jmsexc);
      }
   }
}
               

Save the content. The Developer Studio updates and compiles the project sources.

Result

The MDB has been created in the com.sap.jms.test.MDBEjbBean package. You have also completely implemented the required methods of the MDB.