views:

59

answers:

3

I have a Java project that expects external modules to be registered with it. These modules:

  • Implement a particular interface in the main project
  • Are packaged into a uni-jar (along with any dependencies)
  • Contain some human-readable meta-information (like the module name).

My main project needs to be able to load at runtime (e.g. using its own classloader) any of these external modules. My question is: what's the best way of registering these modules with the main project (I'd prefer to keep this vanilla Java, and not use any third-party frameworks/libraries for this isolated issue)?

My current solution is to keep a single .properties file in the main project with key=name, value=class |delimiter| human-readable-name (or coordinate two .properties files in order to avoid the delimiter parsing). At runtime, the main project loads in the .properties file and uses any entries it finds to drive the classloader.

This feels hokey to me. Is there a better way to this?

A: 

Let all module express their metadata via a standard xml file. Call it "my-module-data.xml".

On your main container startup it looks for a classpath*:my-module-data.xml" (which can have a FrontController class) and delegates to the individual modules FrontController class to do whatever it wants :)

Also google for Spring-OSGI and their doco can be helpful here.

Calm Storm
+4  A: 

The standard approach in Java is to define a Service Provider. See,

http://java.sun.com/j2se/1.4.2/docs/guide/jar/jar.html#Service%20Provider

ZZ Coder
A: 

Expanding on @ZZ Coder...

The Service Provider pattern mentioned, and used internally within the JDK is now a little more formalized in JDK 6 with ServiceLoader. The concept is further expanded up by the Netbeans Lookup API.

The underlying infrastructure is identical. That is, both API use the same artifacts, the same way. The NetBeans version is just a more flexible and robust API (allowing alternative lookup services, for example, as well as the default one).

Of course, it would be remiss to not mention the dominant, more "heavyweight" standards of EJB, Spring, and OSGi.

Will Hartung