After going through the JMS information, you'll probably find it surprisingly simple to code message-driven beans. That's because the container handles all of the steps mentioned in The Java Message Service except actually receiving the messages. In general, the same MDB can be used to receive PTP or pub/sub messages by setting the appropriate ConnectionFactory, destination, and destination type on deployment. As is often the case with EJB technology, some of this coding ease translates into more complexity in the deployment descriptor.
An MDB must have a public, no-arg constructor, and is not allowed to throw application exceptions. In addition, an MDB must implement the following methods (for the life cycle sequence, see Message-Driven Beans Overview):
-
public void setMessageDrivenContext(MessageDrivenContext mdc) — The container normally calls this method exactly once, after instantiation, to pass in the associated MessageDrivenContext.
-
public void ejbCreate() — Called after the setMessageDrivenContext() method. This is a good time to access or obtain any resources that will be used for the life of the bean.
-
public void onMessage(Message msg) — Called by the container when a message has arrived on the bean's associated Queue or Topic. Your code should check for the expected message types, using the instanceof operator, because there is nothing to stop a client from sending any of the available message types. Other than those that deal with the Message object, no JMS methods need be invoked by the bean; it just cracks or parses the received message and performs any associated operations.
-
public void ejbRemove() — Called when the container intends to terminate the bean. All resources should be released at this time.
Once the message has been received, the MDB can perform all the operations itself, or act as a manager, sending the information to and controlling other beans. Queue architecture is fairly limited, because the specification envisions a queue for each bean type. It also warns against deploying multiple beans against the same queue, primarily citing message order concerns; however, there is no guaranteed order for message receipt in any event. The deployment descriptor does allow for JMS message selectors to direct specific messages to a specific bean type.