Google Guice - Overview


Advertisements

Guice is an open source, Java-based dependency injection framework. It is lightweight and is developed as well as managed by Google. This chapter will give you an overview of Guice framework.

Dependency Injection

Every Java-based application has a few objects that work together to present what the end-user sees as a working application. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together and at the same time keeping them independent.

Consider you have an application which has a text editor component and you want to provide a spell check. Your standard code would look something like this −

public class TextEditor {
   private SpellChecker spellChecker;
   
   public TextEditor() {
      spellChecker = new SpellChecker();
   }
}

Note that here we have created a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario, we would instead do something like this −

public class TextEditor {
   private SpellChecker spellChecker;
   
   @Inject
   public TextEditor(SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }
}

Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to the TextEditor at the time of TextEditor instantiation.

Dependency Injection using Guice (Binding)

Dependency Injection is controlled by the Guice Bindings. Guice uses bindings to map object types to their actual implementations. These bindings are defined a module. A module is a collection of bindings as shown below −

public class TextEditorModule extends AbstractModule {
   @Override 
   protected void configure() {
      /*
         * Bind SpellChecker binding to WinWordSpellChecker implementation 
         * whenever spellChecker dependency is used.
      */
      bind(SpellChecker.class).to(WinWordSpellChecker.class);
   }
}

An injector is the object-graph builder and a Module is its core building block. Thus, the first step is to create an injector and then use the injector to get the objects.

public static void main(String[] args) {
   /*
      * Guice.createInjector() takes Modules, and returns a new Injector
      * instance. This method is to be called once during application startup.
   */
   
   Injector injector = Guice.createInjector(new TextEditorModule());
   /*
      * Build object using injector
   */
   TextEditor textEditor = injector.getInstance(TextEditor.class);   
}

In the above example, TextEditor class object graph is constructed by Guice and this graph contains TextEditor object and its dependency as WinWordSpellChecker object.

Advertisements