Google Guice - 链接绑定

在链接绑定中,Guice将类型映射到其实现.在下面的示例中,我们已经将SpellChecker接口与其实现SpellCheckerImpl映射.

bind(SpellChecker.class).to(SpellCheckerImpl.class);

我们还可以将具体类映射到其子类.请参阅下面的示例 :

bind(SpellCheckerImpl.class).to(WinWordSpellCheckerImpl.class);

这里我们链接了绑定.让我们看一下完整示例中的结果.

完整示例

创建一个名为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);
      bind(SpellCheckerImpl.class).to(WinWordSpellCheckerImpl.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." );
   } 
}

//subclass of SpellCheckerImpl
class WinWordSpellCheckerImpl extends SpellCheckerImpl {
   @Override
   
   public void checkSpelling() {
      System.out.println("Inside WinWordSpellCheckerImpl.checkSpelling." );
   } 
}

输出

编译并运行文件,你会看到以下输出.

Inside WinWordSpellCheckerImpl.checkSpelling.