Saturday, August 12, 2006

Sharing common libraries in Java EE

It has always been a bit of an annoyance to share libraries across applications in j2ee applications, involving mucking around with class-path in Manifest.mf files and restrictions etc.,
but with Java EE 5, it has been made easier.

If you want to share common classes and jars it can be put into an ear level directory.

By default this directory is called lib, but if you want a custom name for this directory you can specify it in meta-inf/application.xml, which is really optional for jee5 on
common

The ear level classloader picks up classes from this directory and can be accessed by all the webapps of that ear.

Quoting from the http://java.sun.com/xml/ns/javaee/application_5.xsd schema,

The library-directory element specifies the pathname
of a directory within the application package, relative
to the top level of the application package. All files
named "*.jar" in this directory must be made available
in the class path of all components included in this
application package. If this element isn't specified,
the directory named "lib" is searched. An empty element
may be used to disable searching.

The important thing is that the classes have to be in jars. All jars from lib directory will be automatically loaded.

You can also specify the jars to be loaded shared, via the tag in the application.xml