Java Reference
In-Depth Information
The @MessageDriven annotation marks our class as a message-driven bean. Its
activationConfig attribute accepts an array of @ActivationConfigProperty
annotations, each of which specifies a JMS property name and value. Both the
@MessageDriven annotation and the corresponding @ActivationConfig
annotations are generated automatically from the values we pick on the last
page of the NetBeans New Message-Driven Bean wizard.
Notice that the generated class implements the javax.jms.MessageListener
interface. This is a requirement for message-driven beans. This interface defines
a single method, the onMessage() method, which takes an instance of a class
implementing javax.jms.Message as its sole parameter and returns void. This
method is invoked automatically when a message is received in the JMS destination
where the message-driven bean is listening. We need to add our custom processing
to this method to handle the received message, as shown in the following code:
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("received message: " +
textMessage.getText());
} catch (JMSException ex) {
Logger.getLogger(MessageReceiver.class.getName()).log(
Level.SEVERE, null, ex);
}
}
All JMS message types extend the javax.jms.Message interface. In order to process
the message, we need to cast it to the specific Message subinterface. In our case, the
message we received is an instance of javax.jms.TextMessage .
In our simple example, we simply sent the message content to the application server
log by invoking System.out.println() and passing the value textMessage.
getText() as a parameter. The getText() method of javax.jms.TextMessage
returns a string containing the message text. In a real application, we would do
something more substantial, such as populating database tables from the message
contents or rerouting the message to another JMS destination based on the contents
of the message.
Last but not least, the getText() method of javax.jms.TextMessage can
potentially throw a JMSException ; therefore, we need to add a catch block
to handle the exception.
 
Search WWH ::




Custom Search