Message Driven Bean

Message Driven Bean Tutorial for beginners and professionals. Let see the example of message-driven bean.

Message Driven Bean

Message Driven Bean

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 the message from a queue or topic, so you must have the knowledge of JMS API.

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


Message Driven Bean Example

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

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



  1. import javax.ejb.MessageDriven;  
  2. import javax.jms.*;  
  4. @MessageDriven(mappedName="myTopic")  
  5. public class MyListener implements MessageListener{  
  6.     @Override  
  7.     public void onMessage(Message msg) {  
  8.         TextMessage m=(TextMessage)msg;  
  9.         try{  
  10.         System.out.println("message received: "+m.getText());  
  11.         }catch(Exception e){System.out.println(e);}  
  12.     }  
  13. }  

Export the ejb project and deploy the application.

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

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