background image

Using Message-Driven Beans

<< Produce and Synchronously Receive Messages | Stateless Session Bean >>
<< Produce and Synchronously Receive Messages | Stateless Session Bean >>

Using Message-Driven Beans

You can use bean-managed transactions and the javax.transaction.UserTransaction
interface's transaction demarcation methods, but you should do so only if your application has
special requirements and you are an expert in using transactions. Usually, container-managed
transactions produce the most efficient and correct behavior. This tutorial does not provide any
examples of bean-managed transactions.
Using Message-Driven Beans to Receive Messages
Asynchronously
The sections
"What Is a Message-Driven Bean?" on page 634
and
"How Does the JMS API
Work with the Java EE Platform?" on page 896
describe how the Java EE platform supports a
special kind of enterprise bean, the message-driven bean, which allows Java EE applications to
process JMS messages asynchronously. Session beans allow you to send messages and to receive
them synchronously but not asynchronously.
A message-driven bean is a message listener that can reliably consume messages from a queue
or a durable subscription. The messages can be sent by any Java EE component (from an
application client, another enterprise bean, or a web component) or from an application or a
system that does not use Java EE technology.
Like a message listener in a stand-alone JMS client, a message-driven bean contains an
onMessage
method that is called automatically when a message arrives. Like a message listener,
a message-driven bean class can implement helper methods invoked by the onMessage method
to aid in message processing.
A message-driven bean, however, differs from a stand-alone client's message listener in the
following ways:
Certain setup tasks are performed by the EJB container.
The bean class uses the @MessageDriven annotation to specify properties for the bean or the
connection factory, such as a destination type, a durable subscription, a message selector, or
an acknowledgment mode. The examples in
Chapter 32, "Java EE Examples Using the JMS
API"
show how the JMS resource adapter works in the Application Server.
The EJB container automatically performs several setup tasks that a stand-alone client has to
do:
Creating a message consumer to receive the messages. Instead of creating a message
consumer in your source code, you associate the message-driven bean with a destination
and a connection factory at deployment time. If you want to specify a durable subscription
or use a message selector, you do this at deployment time also.
Registering the message listener. You must not call setMessageListener.
Specifying a message acknowledgment mode. The default mode, AUTO_ACKNOWLEDGE, is used
unless it is overriden by a property setting.
Using the JMS API in a Java EE Application
The Java EE 5 Tutorial · September 2007
956