November 13, 2003

Using JMX to Initialize JBoss App.

See J2EE Application Startup Code for a discussion of different approaches to having startup code executed in a J2EE application. JBoss provides an elegant solution to the problem of needing startup code to run in the same JVM as an application, but outside of the EJB container. The solution is to bind JMX MBeans to an application's environment. Here's how.

Create an MBean interface that defines start and stop methods.

public interface StartupMBean
{
   public void start() throws Exception;
   public void stop() throws Exception;
}

Create an MBean class that implements your interface.

public class Startup implements StartupMBean
{
   public void start() throws Exception
   {
       // Perform initialization here.
   }

   public void stop() {}
}

Create a jboss-service.xml file.

<server>
   <mbean code="mypackage.Startup" name="myapp:service=Startup">
   </mbean>
</server>

Create an application.xml file.

<!DOCTYPE application PUBLIC
"-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
"http://java.sun.com/dtd/application_1_3.dtd">

<application>
   <display-name>EJB ear</display-name>
   <module>
       <ejb>myapp-ejbs.jar</ejb>
   </module>
</application>

Create a jboss-app.xml file.

<jboss-app>
   <module>
       <service>myapp.sar</service>
   </module>
</jboss-app>

Package everything as follows.

myapp.ear
+- META-INF/MANIFEST.MF
+- META-INF/application.xml
+- META-INF/jboss-app.xml
+- myapp-ejbs.jar (archive) [EJB jar]
+- myapp.sar (archive) [MBean sar]
|  +- META-INF/MANIFEST.MF
|  +- META-INF/jboss-service.xml
|  +- mypackage/Startup.class
|  +- mypackage/StartupMBean.class

The .sar file (which stands for service application archive) is just a regular .jar file with a .sar extension instead of .jar.

Now, each time that you deploy myapp.ear, the start method of Startup will be called, executing your startup code. Startup has access to all of the classes in myapp-ejbs.jar since it runs in the same JVM as your ejbs.

Viola! Startup code in JBoss!

Posted by tomlauren at November 13, 2003 06:13 PM
Comments

Hi,

I'm implementing something similar to what you have mentioned. I have tried it out, and your explaination were clear to understand. Thanks.
But I have a problem, when I try to deploy it, the start method activate before the EJBModules are fully deloyed. and this caused error since the start method relies on some of the EJBs. Please help..Thank you.

Posted by: Michelle at April 18, 2004 09:03 PM