Module initialization order in Java EE 6

July 23, 2010 Comments Off

One of the new features in the umbrella Java EE 6 specification is the ability to define the order in which modules (web applications for instance) from a given Java EE application are initialized by the container. This might be useful if you want for example a given module to serve as resource initializer to create a database table before any other module can be accessed (note this does not apply to application client modules). Previously, the order in which Java EE application modules were initialized was unspecified and by default this is still the case in Java EE 6.

To explicitly request modules to be started in a particular order, the application should use <initialize-in-order>true</initialize-in-order> in the the EAR’s application.xml deployment descriptor. The container will then start the modules in the order they are declared in that same configuration file (note that application.xml is optional by default and should be placed in the EAR’s top-level META-INF/ directory). The short example below shows an EJB singleton creating a database table upon creation and dropping it before destruction. With this setup, the database table should always be accessible to the web application.

InitDB.java (a singleton packaged in OrderMatters-ejb.jar) :


@Singleton
@Startup
public class InitDB {
     @PostConstruct
     void createDBtable() {
         //...
     }

     @PreDestroy
     void dropDBtable() {
         //...
     }
}

The application.xml deployment descriptor for OrderMatters.ear :

<application version="6"
         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/application_6.xsd">
     <initialize-in-order>true</initialize-in-order>
     <display-name>OrderMatters</display-name>
     <module>
         <ejb>OrderMatters-ejb.jar</ejb>
     </module>
     <module>
         <web>
             <web-uri>OrderMatters-war.war</web-uri>
             <context-root>OrderMatters-war</context-root>
         </web>
     </module>
</application>

Full details are available in the Java EE 6 platform specification, section EE.8.5.4. Of course you can use this today in GlassFish.

As an alternate solution if you’re willing to use features in GlassFish 3 beyond what Java EE 6 provides, you may also solve the problem by breaking the application into different OSGi bundles and using a combination of BundleActivator and ServiceTracker as shown in this sample from Sahoo). This can in some cases offer a more suitable and loosely-coupled approach.

About these ads

Comments are closed.

What’s this?

You are currently reading Module initialization order in Java EE 6 at Bistro! 2.0.

meta

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: