Message Driven Bean
Message Driven Bean Tutorial for beginners and professionals. Let see the example of 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:
File: MyListener.java
- 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.
Now send the message using JMS that is covered in the previous page.