Starting Components On Java EE 5 Appserver In a Portable Way

The last time I was frequently asked how to start components / initialize the infrastructure during server's startup. I saw several solutions already, some really esotheric, most of them not portable across servers. However the solution is really simple. All you need is a servlet with an init method:

public class BootstrapServlet extends HttpServlet {   

     //optional, only needed in case you would like to startup a session bean as well
    private BootstrapBean bootstrap;
    public void init(){
        System.out.println("##################################### Hello World init");

   public void doGet...


 To cause the application to init the servlet at startup, you have to include the <load-on-startup> tag in the web.xml.

 <web-app version="2.5" xmlns="" xmlns:xsi="" xsi:schemaLocation="">


The spec says: "...The load-on-startup element indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these
        element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet
        whenever it chooses. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that
        servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value...

If you would like to initialize a Session Bean during the startup just inject the Session Bean into the servlet -> and it has to be initialized to. The EJB 3.1 spec will come with a Singleton Bean which will solve this problem - even without a servlet... I checked in this sample code as a Netbeans 6.1/Glassfish v2 into, the project name is ServletBootStrapping.

Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition the podcast:

Stay in touch:


Good tip.

EJB 3.1 Spec will based this Singleton Bean initialization mechanism with an annotation "@Startup".

Posted by petrus on March 19, 2008 at 10:41 AM CET #

Thank you for the article, but doesn't work in clustered environment, where, for example, a timer would be scheduled twice.

Posted by Luca Masini on August 14, 2011 at 12:40 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments