- A Message Driven Bean (further referred to as MDB) is just another EJB like Stateless, Stateful or a Singleton. It’s specified using the @MessageDriven annotation.
- MDBs are used for asynchronous message processing
- They are similar to Stateless EJBs since both of them are pooled by the EJB container
- However they differ from Stateless EJBs since MDBs cannot be directly accessed by a client. Only the container calls them in response to a message sent by the client to an endpoint which the MDB is listening to.
Commonly used pattern for MDB
- MDBs are generally used along with JMS (Java Message Service API)
- A MDB is configured to listen to a JMS destination using @ActivationConfigProperty, implements the javax.jms.MessageListener interface and provides the business logic (message processing) in the onMessage method
- A component sends a Message to the JMS destination (end point). This is not a synchronous process (as already mentioned above). The message firing method returns immediately and the container takes care of calling the MDB configured to listen that particular JMS destination
- MDBs are not part of the JMS spec or coupled with JMS by any means – this is a misconception.
- MDB are pooled beans which can process messages in an async fashion and can listen to any end point including a JMS queue or destination (most generally seen).
- In fact, this has been the case since EJB 2.1 and is made possible by the JCA (Java Connector Architecture) spec
What’s JCA ?
- On a high level, JCA enables Java EE servers to interact with external systems e.g. legacy enterprise information sources etc via a standard SPI (not dealing with intricate JCA details here)
- One can use the JCA standard interfaces to build a Resource Adapter (RAR file) for a specific system
- JCA provides contracts for two-way communication (inbound and outbound) b/w the Java EE container and the external system – the implementation for which needs to be present withing the Resource Adapter itself
How does JCA enable the concept of Generic MDBs ?
- JCA defines MDB specific features
- Just like in the case of a JMS based MDB, a JCA based MDB also needs to implement an interface and define activation properties (both are specific to the JCA Resource Adapter implementation)
- The external system sends a message which the Resource Adapter accepts via its implementation of the inbound JCA contract and this message is relayed to an internal endpoint (this is again specific to the JCA adapter implementation)
- The MDB registered to this endpoint kicks in an executes the business logic on the received message
An external system sending messages to a Java EE container using a standard interface (JCA) while the JCA implementation takes care of delivering it to the appropriate endpoint which further delivers it to the registered MDB
Thing to notice is that this is completely portable across Java EE servers since, EJB spec vendors have to support JCA based MDBs.