Guice-binding-annotations
提供:Dev Guides
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.