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:
startupServlet
com.j2eegeek.servlet.util.StartupServlet
9
startupServlet
/startupServlet
Here’s the fully commented servlet (HTML | Java) that does the acts as my startup class. Comments on other ideas are always welcome.