- 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 - 繫結註解
由於可以將型別與其實現繫結。在希望用多個實現對映型別的情況下,我們還可以建立自定義註解。請參閱以下示例以瞭解概念。
建立繫結註解
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface WinWord {}
@BindingAnnotation - 標記註解為繫結註解。
@Target - 標記註解的適用性。
@Retention - 標記註解的可用性為執行時。
使用繫結註解對映
bind(SpellChecker.class).annotatedWith(WinWord.class).to(WinWordSpellCheckerImpl.class);
使用繫結註解注入
@Inject
public TextEditor(@WinWord SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
完整示例
建立一個名為 GuiceTester 的 java 類。
GuiceTester.java
import java.lang.annotation.Target;
import com.google.inject.AbstractModule;
import com.google.inject.BindingAnnotation;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface WinWord {}
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(@WinWord SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void makeSpellCheck(){
spellChecker.checkSpelling();
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(SpellChecker.class).annotatedWith(WinWord.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.
廣告