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.