Saturday, December 15, 2007

Simple Dependency Injection with Guice

Google's Guice is a very slick, annotations-based Dependency Injection framework. It allows you to easily create class instances even if they have complex dependencies on other classes. The knowledge of what concrete implementation to use for a dependency is contained in simple configuration classes called Modules. Injection sites for these implementations may be constructors, methods, or fields. Anywhere you want a dependency to be injected you just add the @Inject annotation to. The is pretty much all there is too it. Guice is very simple and has a relatively small learning curve.

Here is a code snippet showing injection of a dependancy into a constructor:

@Inject
public TimeChecker(IClock clock) { ... }


And here is the Module to tell Guice which concrete implementation to use:

@Inject
public TimeChecker(IClock clock) { ... }


Now to get an instance of TimeChecker you no longer need to build it's dependancies:

TimeChecker timeChecker = Guice.createInjector(new ProductionSettingsModule()).getInstance(TimeChecker.class);


For one dependency this looks like a lot of work, but if your class has four or five dependencies the above line does not get any bigger.

No comments: