Thursday, December 27, 2007

ServiceLoader

In Java 6 sun introduces the ServiceLocator class. It's an interesting implementation of the Service Locator Pattern.

Before, the way to perform service look-ups usually involved creating some kind of object registry and/or used JNDI. I even created an example service locator using JNDI quite a few years ago. Though completely obsolete now, I've long since switched to the Spring Framework's JndiObjectFactoryBean.

This new facility allows you to swap implementations by swapping out jars on the classpath. Though I expect the actual usage to be pretty limited as dependency injection frameworks are pretty well dominating the development scene. The primary use will most likely be for libraries that implement common APIs.

I can see an interesting use though. There is a growing trend (that I've been pushing myself for about 5 years now) of writing configuration in a programming language, like java. The idea being that the configuration can be validated by a compiler, and maintained with advanced development tools. Imagine completely separating the configuration from the application. If a framework like Spring is used, a factory class can be created that performs the service look-up for the rest of the application's configuration. Then application configuration can be handled by dropping in a small jar, instead of rebuilding the entire application.

The downside? Creating a text file under the META-INF directory. Sound bad? yes. But, I actually believe this will be the greatest hindrance to broad adoption. Laugh if you will. A text file, whose name is the interface name containing the name of the implementation class (nothing else) may be the 2nd biggest blocker (the first being D.I.). Unfortunately, about 90%+ of the Java devs I know don't know how to add items to the manifest of a jar, and/or don't even know what its for. Most people seem to think there's a lot of voodoo in the meta data directory and are scared to touch it.

Though this is a cool new feature for Java, it would have been more useful about 7 years ago. D.I. has really made the Service Locator pattern mostly obsolete. My best answer why, I've noticed that the popularity of D.I. is directly proportional to the popularity of unit testing. Simply put, D.I. makes for classes that are easier to test. Testing in a look-up environment usually involves creating a stub (mock if you will) factory that can return test implementations of interfaces. A lot of work when the tests will be simple.
.
.

Labels: , , ,

permalink
Links to this post

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home

Links to this post on: