Java Reference
In-Depth Information
@PreDestroy
void closePrintWriter() {
printWriter.flush();
printWriter.close();
}
The container will call the
closePrintWriter
right before the container removes it
from the pool. Upon getting called, the MDB instance will flush whatever contents may be
in the
PrintWriter
buffer, and then it closes to release the file resources.
Now you may be asking yourself, is it safe to be writing to a file like this when the con-
tainer can create multiple instances of an MDB and pool them for efficient processing of
messages? The answer is probably not. But this was just a simple example to demonstrate
how the
PostConstruct
and
PreDestroy
lifecycle callback methods may be used in
an MDB.
An MDB is great for receiving and processing messages. We've just finished covering the
basics of this. But can an MDB also send messages? The answer is yes, and you may find
yourself doing this more often than you'd think. We'll explore how MDBs can send JMS
messages next.
4.3.8. Sending JMS messages from MDBs
Somewhat ironically, a task you find yourself performing time and time again in an MDB
is sending JMS messages. As a simple example, suppose that you have an incomplete ship-
ping request and you need to communicate that back to ActionBazaar from the
Ship-
pingRequestProcessor
. The easiest way to handle this notification is via JMS
messages sent to an error queue that ActionBazaar is monitoring. Fortunately, you've
already seen how to send a JMS message in
listing 4.1
. You inject the queue named
jms/ShippingErrorQueue
and the connection factory named
jms/QueueCon-
nectionFactory
:
@Inject
@JMSConnectionFactory("jms/QueueConnectionFactory")
private JMSContext context;
@Resource(name="jms/ShippingErrorQueue")
private Destination errorQueue;