Java Reference
In-Depth Information
You also inject the queue to forward the shipping request to, aptly named Ship-
pingRequestQueue , using the @Resource annotation
.
This code example is from a servlet that uses the annotations for injection. The servlet con-
tainer automatically looks up the resources registered in JNDI and injects them. Chapter 5
discusses dependency injection in greater detail.
Preparing the message
In this example, you want to send the Serializable Java object ShippingRequest
to Turtle. So you create a new instance of the object and set its data . After doing this,
you need to determine which JMS message type you need in order to send this object.
The most appropriate message type is javax.jms.ObjectMessage . You use your
JMSContext to create an ObjectMessage and set the ShippingRequest inside
. Now that you have your message ready to send, the only thing left to do is send it.
Sending the message
A JMSProducer is used to send a message. As in preparing the message, the JMSCon-
text is your source for the producer. Simply call the createProducer method and
send the message you just created . It doesn't get much simpler than that! After sending
your message, you have one more thing to worry about. You need to clean up the resources
you've used—or do you?
Releasing resources
The great thing about using dependency injection in a managed environment is that the
container can take care of a number of very important things for you. Releasing resources
is one of them. The previous code example is from a Servlet, and because of this the
JMSContext is a container-managed resource. That means the container will handle clos-
ing the resource for you. The JMSContext does have a close method, however. If you
obtain a JMSContext from a nonmanaged environment—such as creating one from a
ConnectionFactory in a Java SE application—you do need to manually clean things
Search WWH ::




Custom Search