adam bien's blog

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
    @EJB
    private BootstrapBean bootstrap;
   
    @Override
    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="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>BootstrapServlet</servlet-name>
        <servlet-class>com.abien.bootstrap.BootstrapServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>BootstrapServlet</servlet-name>
        <url-pattern>/BootstrapServlet</url-pattern>
    </servlet-mapping>
 </web-app>

 

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 http://p4j5.dev.java.net, the project name is ServletBootStrapping.