Friday, July 18, 2008

Google Guice - 谷歌的果汁

Guice (pronouced 'juice') is a new dependency injection framework from Google. The biggest difference between Guice and other DI framework is the annotation. Guice does not use xml configuration. Instead, you mark your 'injectee' with the @Inject annotation. This annotation tell Guice: "Hello injector, I need your help. Try to find the dependencies for me".  The concept is very simple, and it really takes only 10 minutes to get started.  Of course, this assumes you already know what DI is, which might take a while to put it into practice.

The class dependency is organized in a Module. In the module, you bind an interface to a concrete implementation.  Just like all DI framwork, the purpose is to avoid using the new operation.  When you say Animal a = new Dog(); you hardcoded the Dog type in the source code.  If you run it the Guice way, you will create a AnimalModule,  and bind the Dog object within the AnimalModule. Next time when you want to switch the implementation, simply change the Module, not your code.

 public class AnimalModule implements Module {

public void configure(Binder binder) {

binder.bind(Animal.class).to(Dog.class);

}

}


Guice also provide support of field injection. You can initialize field values in a module, even for private fields.  Unlike Spring, which want to be a replacement of everything, Guice limit itself to be a simple layer focus on dependency injection.

If you really want to know the disadvantage of Guice compare to other pre Java 5 DI frameworks, the only thing I can think of is the jar dependency.  Once you decide to use Guice annotation, you must include guice jar file in your classpath.  Some other DI framework like Spring or Pico can retrofit into old classes without touching the code.  This is not the case for Guice.

If you want to start a new project and want to have a light DI layer quickly, Guice is really worth trying.




No comments: