This post originated from an RSS feed registered with Java Buzz
by Vinny Carpenter.
Original Post: J2EE Startup/Shutdown classes
Feed Title: Vinny Carpenter's Blog
Feed URL: http://www.j2eegeek.com/error.html
Feed Description: Welcome to my blog. I am a total Java geek that lives in Milwaukee, making my living as an architect/developer, spending all my time with Java, J2EE, OO, Linux, and open source. In my spare time, when I am not in front of my computers, I spend every other minute with my other loves: My wife, books, music, guitars, Formula-1 racing and StarGate. Check out my blog @ http://www.j2eegeek.com/blog
Debu Panda had an interesting blog entry about something that's always bugged me. Most J2EE applications require you to invoke some functionality at the server startup or application deployment time. For example, you may want to preload some data cache or invoke some business logic or invoke some logic at server shutdown to gracefully disconnect from some service you're connected to or release some resource. As Debu points out in his blog entry, each container vendor offers a proprietary way to do this. I think this is a huge deficiency in the J2EE specification and I hope it is something that's addressed in the next iteration of the specification.
I've come up with a solution that I have used over the years that is container independent for applications deployed in WebLogic, JBoss and Tomcat. It's not really rocket science, but I use a Servlet as my startup and shutdown class by taking advantage of the servlet lifecycle and the init() and destroy() methods.
Most web containers will create an instance of the servlet by calling the no-args constructor. Once the instance is created, the container will then call the Servlet's init() method. The init() method is guaranteed to be called only once during the Servlet's lifecycle which makes it use as a startup class work perfectly. The same goes for the destroy() method, which is also guaranteed to be called only once and that makes it an ideal candidate as a shutdown class.
To load the servlet on deployment or server start-up, just enable the load-on-startup attribute of the servlet. Here's what the web.xml looks like for the startup servlet:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">