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.
Pingback: Google Guice and Apache MyFaces 1.2.x « Matthias Wessendorf’s Weblog
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
Pingback: Die Kraft des Saftes: Dependency Injection « eSCALAtion Blog