Google Guice - 第一個應用程式




我們建立一個基於樣例控制檯的應用程式,逐步演示使用 Guice 繫結機制實現依賴注入。

步驟 1:建立介面

//spell checker interface
interface SpellChecker {
   public void checkSpelling();
}

步驟 2:建立實現

//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
   @Override
   public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
   } 
}

步驟 3:建立繫結模組

//Binding Module
class TextEditorModule extends AbstractModule {
   @Override
   protected void configure() {
      bind(SpellChecker.class).to(SpellCheckerImpl.class);
   } 
}

步驟 4:建立具有依賴關係的類

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

步驟 5:建立 Injector

Injector injector = Guice.createInjector(new TextEditorModule());

步驟 6:獲取滿足依賴關係的物件。

TextEditor editor = injector.getInstance(TextEditor.class);

步驟 7:使用物件。

editor.makeSpellCheck(); 

完整示例

建立一個名為 GuiceTester 的 Java 類。

GuiceTester.java

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

public class GuiceTester {
   public static void main(String[] args) {
      Injector injector = Guice.createInjector(new TextEditorModule());
      TextEditor editor = injector.getInstance(TextEditor.class);
      editor.makeSpellCheck(); 
   } 
}

class TextEditor {
   private SpellChecker spellChecker;

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

   public void makeSpellCheck(){
      spellChecker.checkSpelling();
   }
}

//Binding Module
class TextEditorModule extends AbstractModule {

   @Override
   protected void configure() {
      bind(SpellChecker.class).to(SpellCheckerImpl.class);
   } 
}

//spell checker interface
interface SpellChecker {
   public void checkSpelling();
}


//spell checker implementation
class SpellCheckerImpl implements SpellChecker {

   @Override
   public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
   } 
}

輸出

編譯並執行該檔案,您將看到以下輸出。

Inside checkSpelling.
廣告
© . All rights reserved.