Creating Google Guice Modules with Java 6′s ServiceLoader

Google Guice is a lightweight dependency injection framework for Java 5 (or later), which is explained here very well.

To actually map an interface to its implementation, you write Modules (by implementing Module interface or extending AbstractModule), containing code like:


bind(Service.class).to(ServiceImpl.class);
bind(Service.class).annotatedWith(Secure.class)
  .to(SecureServiceImpl.class);

At runtime, when launching your server/program, you typically create an instance of the before written Module:


Injector injector = Guice.createInjector(
  new DefaultModule(), ...);

The above createInjector() uses Java’s varargs syntax to take multiple Module clazzes.Wouldn’t it be nice to load those modules dynamically?Yes! And it is possible, by using Java 6′s ServiceLoader class.It is pretty simple and straightforward. Just create a text-file in META-INF/services, that is named “com.google.inject.Module”. Since Guice’s Module is representing the desired service. Inside this text-file, list all your modules with their fully-qualified class name, such as net.wessendorf.DefaultModule. One Module per line. Now your code looks like:


ServiceLoader<com.google.inject.Module> modules =
  ServiceLoader.load(com.google.inject.Module.class);
Injector injector = Guice.createInjector(modules);

The overloaded createInjector() method now takes an Iterable<Module>. This means, that all your Modules (defined in META-INF/services/com.google.inject.Module) are now available.

Apache Trinidad – new releases

As a happy new year “present”, today we (Apache MyFaces) released Trinidad 1.0.5 (for JSF 1.1) and Trinidad 1.2.5 (for JSF 1.2).

We now have two trunks, so we ship both releases on the same date. Before it wasn’t the case, because the Trinidad 1.2.x release was created out of the TAG that was used for the 1.0.x release.

Life is easy now :-)

Have fun with Trinidad 1.0.5 OR 1.2.5.

In case you use Trinidad, would be cool if you add your company to this page.