A message driven bean (MDB) is a bean that contains business logic. But, it is invoked by passing the message. So, it is like JMS Receiver.

MDB asynchronously receives the message and processes it.

A message driven bean receives message from queue or topic, so you must have the knowledge of JMS API.

A message driven bean is like stateless session bean that encapsulates the business logic and doesn’t maintain state.

message driven bean

Message Driven Bean Example

To create the message driven bean, you need to declare @MessageDriven annotation and implement MessageListener interface.

In eclipse ide, create EJB Project then create a class as given below:

File: MyListener.java

package com.javatpoint;  
import javax.ejb.MessageDriven;  
import javax.jms.*;  
  
@MessageDriven(mappedName="myTopic")  
public class MyListener implements MessageListener{  
    @Override  
    public void onMessage(Message msg) {  
        TextMessage m=(TextMessage)msg;  
        try{  
        System.out.println("message received: "+m.getText());  
        }catch(Exception e){System.out.println(e);}  
    }  
}

Export the ejb project and deploy the application.

In glassfish server, click on applications -> deploy -> select mdb jar file by Choose File -> OK.

how to deploy mdb

Now send the message using JMS that is covered in the previous page.

ejb message driven bean output