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.

Howdy!

Posted in guice, java
3 comments on “Creating Google Guice Modules with Java 6’s ServiceLoader
  1. […] news is, that when you use Java6, you can use ServiceLoader class to load the Guice modules (see here as well). So… we could use a more generic ServletContextListener for the “guice […]

  2. Andrew Clegg says:

    Just come across this post, a year late🙂

    This is a neat trick, and one that might be useful elsewhere, but… Isn’t the point of Guice to do *more* in Java code and *less* in config files, so your IDE can notice bugs before compiling?

    Otherwise you may as well use Spring😉

  3. […] weil man ja dem Injector alle Module „hartkodiert“ übergeben muss, aber es fand sich (hier) eine elegante Lösung: Der ServiceLoader von Javas eingebauten SPI-Mechanismus. Das sieht dann […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: