English 中文(简体)
Guice - Overview
  • 时间:2024-12-22

Google Guice - Overview


Previous Page Next Page  

Guice is an open source, Java-based dependency injection framework. It is quiet pghtweight and is actively developed/managed by Google.

Dependency Injection

Every Java-based apppcation has a few objects that work together to present what the end-user sees as a working apppcation. When writing a complex Java apppcation, apppcation classes should be as independent as possible of other Java classes to increase the possibipty 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 apppcation which has a text editor component and you want to provide a spell check. Your standard code would look something pke this −


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

What we ve done here is, create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario, we would instead do something pke this −


pubpc class TextEditor {
   private SpellChecker spellChecker;
   
   @Inject
   pubpc 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:


pubpc 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);
   }
}

The Module is the core building block for an Injector which is Guice s object-graph builder. First step is to create an injector and then we can use the injector to get the objects.


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

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

Advertisements