Google Guice - 概述



Guice是一個基於Java的開源依賴注入框架。它非常輕量級,並由Google積極開發/維護。

依賴注入

每個基於Java的應用程式都有一些物件協同工作,終端使用者看到的只是一個工作的應用程式。在編寫複雜的Java應用程式時,應用程式類應該儘可能獨立於其他Java類,以增加重用這些類的可能性,並在單元測試時獨立於其他類進行測試。依賴注入(有時稱為連線)有助於將這些類粘合在一起,同時保持它們的獨立性。

假設您有一個包含文字編輯器元件的應用程式,並且您想提供拼寫檢查功能。您的標準程式碼如下所示:

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

我們在這裡所做的是在TextEditor和SpellChecker之間建立依賴關係。在控制反轉的情況下,我們將改為執行以下操作:

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

在這裡,TextEditor無需擔心SpellChecker的實現。SpellChecker將獨立實現,並在TextEditor例項化時提供給TextEditor。

使用Guice進行依賴注入(繫結)

依賴注入由Guice繫結控制。Guice使用繫結將物件型別對映到它們的實際實現。這些繫結在一個模組中定義。模組是繫結集合,如下所示

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

模組是Injector的核心構建塊,Injector是Guice的物件圖構建器。第一步是建立一個Injector,然後我們可以使用Injector來獲取物件。

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

在上面的示例中,TextEditor類的物件圖由Guice構建,該圖包含TextEditor物件及其依賴項WinWordSpellChecker物件。

廣告
© . All rights reserved.