The Message-Driven Bean Class
The code for the
SimpleMessageBeanclass illustrates the requirements of a message-driven bean class:
- It must implement the message listener interface for the message type it supports. A bean that supports the JMS API implements the
javax.jms.MessageListenerinterface.- It must be annotated with the
MessageDrivenannotation if it does not use a deployment descriptor.- The class must be defined as
public.- The class cannot be defined as
abstractorfinal.- It must contain a public constructor with no arguments.
- It must not define the
finalizemethod.Unlike session beans and entities, message-driven beans do not have the remote or local interfaces that define client access. Client components do not locate message-driven beans and invoke methods on them. Although message-driven beans do not have business methods, they may contain helper methods that are invoked internally by the
onMessagemethod.The
MessageDrivenannotation typically contains amappedNameelement that specifies the JNDI name of the destination from which the bean will consume messages. For complex message-driven beans there can also be anactivationconfigelement containingActivationConfigPropertyannotations used by the bean. See A Java EE Application That Uses the JMS API with a Session Bean (page 1096) for an example.A message-driven bean can also inject a
MessageDrivenContextresource. Commonly you use this resource to call thesetRollbackOnlymethod to handle exceptions for a bean that uses container-managed transactions.Therefore, the first few lines of the
SimpleMessageBeanclass look like this:@MessageDriven(mappedName="jms/Queue") public class SimpleMessageBean implements MessageListener { @Resource private MessageDrivenContext mdc; ...The onMessage Method
When the queue receives a message, the EJB container invokes the message listener method or methods. For a bean that uses JMS, this is the
onMessagemethod of theMessageListenerinterface.A message listener method must follow these rules:
The
onMessagemethod is called by the bean's container when a message has arrived for the bean to service. This method contains the business logic that handles the processing of the message. It is the message-driven bean's responsibility to parse the message and perform the necessary business logic.The
onMessagemethod has a single argument: the incoming message.The signature of the
onMessagemethod must follow these rules:In the
SimpleMessageBeanclass, theonMessagemethod casts the incoming message to aTextMessageand displays the text:public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { msg = (TextMessage) inMessage; logger.info("MESSAGE BEAN: Message received: " + msg.getText()); } else { logger.warning("Message of wrong type: " + inMessage.getClass().getName()); } } catch (JMSException e) { e.printStackTrace(); mdc.setRollbackOnly(); } catch (Throwable te) { te.printStackTrace(); } }