Tuesday, August 12, 2008

Controlling class loading in j2ee application

In some cases, we might have to change the order of class loading from different jar. This can be easily controlled for stand alone applications, Change the CLASSPATH to add a jar which need precedence in the first place. For example,

old.jar conatins Function.class file, this has to be modified to use new functionality. So team has developed new.jar with Function.class file. To keep backward compatability we need to maintain both the jars. To make new.jar Function.class precedence add them to class path as below

CLASSPATH=new.jar;old.jar;other.jar

This works great, simple and easy!!!

What happens if we need to follow same in J2EE application? Can you control order of classloading? Yes you can, but need to follow few steps. Before moving on lets consider ear package as below

j2eestandard.ear
ejb.jar
web.war
lib/old.jar
lib/new.jar
lib/other.jar

In this sample package, APP server loads calsses in following order
  1. First it loads all the classes under lib folder (the jar file order can vary to environment to environment, so we cannot predict old.jar or new.jar gets loaded?). Then appserver refers any manifest:classpath is specified in the jar files under lib folder. If it is specified that will be loaded
  2. Second step, ejb jars will be loaded (in this case ejb.jar). If there is any manifest:classpath in ejb.jar then that will also be loaded
  3. Finally web app will be loaded (web.war), If there is any manifest:classpath in web.war, that will also be loaded.

So now we have got an overview, now time to tweak a bit to make sure to load new.jar first. As per step 1, all the jars in /lib/ will be loaded first. So keep new.jar under lib folder. Move old.jar to root. Add manifest to ejb.jar and mention about old.jar, as below




j2eemodified.ear
ejb.jar
MANIFEST.MF
Manifest-Version: 1.0
Class-Path: old.jar
web.war
lib/new.jar
lib/other.jar
old.jar

The classes will be loaded in below order now,

  1. All the jars under lib folder, so new.jar and other.jar
  2. ejb.jar, there is manifest info so
  3. old.jar will be loaded
  4. web.war will be loaded

Its solved now. Happy packaging !!! :)