Show TOC

Developing the Message-Driven Bean Locate 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 3.0 Project, choose   New...   Other...   EJB...   Message-Driven Bean  . Choose Next.

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

  3. Select the JMS checkbox and select Queue in the Destination type drop down 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. 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:

Syntax Syntax

  1. 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);
          }
       }
    }
End of the code.

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.