Page 1 of 2
Message-driven beans (MDBs) are stateless, server-side, transaction-aware components for processing asynchronous JMS messages. Introduced since EJB 2.0, message-driven beans process messages delivered via the Java Message Service.
Message-driven beans can receive JMS messages and process them using the same robust component-based infrastructure that session and entity beans enjoy. While a message-driven bean is responsible for processing messages, its container takes care of automatically managing the component’s entire environment including transactions, security, resources, concurrency, message
acknowledgment, etc.
One of the most important aspects of MDBs is that they can consume and process messages concurrently. This capability provides a significant advantage over traditional JMS clients, which must be custom-built to manage resources, transactions, and security in a multi-threaded environment.
Before the release 3.0 of EJB also MDB needed a configuration file describing its properties, now let's see an example of MDB using annotations. it turns out that writing an MDB is just a matter of a few minutes:
<
package com.sample;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
@MessageDriven(name = "MessageMDBSample", activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/MyQueue"),
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })
public class DummyMDBean implements MessageListener {
@Resource
private MessageDrivenContext context;
@Resource(mappedName = "OracleDS")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@PostConstruct
public void initialize() {
try {
connection = dataSource.getConnection();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
@PreDestroy
public void cleanup() {
try {
connection.close();
connection = null;
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
public void onMessage(Message message) {
try {
Statement statement = connection.createStatement();
statement.execute("INSERT INTO ...........");
} catch (JMSException jmse) {
jmse.printStackTrace();
context.setRollBackOnly();
} catch (SQLException sqle) {
sqle.printStackTrace();
context.setRollBackOnly();
}
}
}