Java Reference
In-Depth Information
• When the
onMessage
method finishes executing, it pushes the idle bean back in-
to the method-ready pool.
• As needed, retires (and destroys) beans out of the pool.
The MDB's two lifecycle callbacks are
PostConstruct
, which is called immediately
after an MDB is created and set up and all the resources are injected, and
PreDestroy
,
which is called right before the bean instance is retired and removed from the pool. These
callback methods can be used for any kind of operations you want, but typically they're
used for creating and cleaning up resources used by the MDB. As a simple example, let's
suppose your MDB needs to write a file on the file system. To do this, a
PrintWriter
is first needed. You can easily define a
PrintWriter
in the MDB class like this:
PrintWriter printWriter;
Now you need to initialize the
printWriter
property, which you do by using a
PostConstruct
lifecycle method, which may look like the following:
@PostConstruct
void createPrintWriter() {
File f = new File(new File(System.getProperty("java.io.tmpdir"))
, "ShippingMessages.txt");
try {
printWriter = new PrintWriter(f);
} catch (Throwable t) {
throw new RuntimeException(t);
}
Logger.getLogger(TurtleShippingRequestMessageBean.class.getName())
.log(Level.INFO,
String.format("Write to file: %s", f.getAbsolutePath()));
}
When the MDB is created by the container, it'll run the
createPrintWriter
method,
which will initialize the
printWriter
property. The
printWriter
property can now
be used by the
onMessage
method or any method in the MDB to write to the file while
the MBD is active.
When the container decides to get rid of the MDB and destroy the instance, it's time to
clean up the file resource. You do this with a
PreDestroy
lifecycle method, which looks
something like this: