- Google Guice 教程
- Guice - 首頁
- Guice - 概述
- Guice - 環境設定
- Guice - 第一個應用程式
- 繫結示例
- Guice - 連結繫結
- Guice - 繫結註解
- Guice - @Named 繫結
- Guice - 常量繫結
- Guice - @Provides 註解
- Guice - 提供程式類
- Guice - 建構函式繫結
- Guice - 內建繫結
- Guice - 即時繫結
- 注入示例
- Guice - 建構函式注入
- Guice - 方法注入
- Guice - 域注入
- Guice - 可選注入
- Guice - 按需注入
- 其他示例
- Guice - 作用域
- Guice - AOP
- Guice 有用資源
- Guice - 快速指南
- Guice - 有用資源
- Guice - 討論
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.
廣告