依存性のバインディング
How does Guice know what to inject? For starters, a Key composed of a type and an optional annotation uniquely identifies a dependency. Guice refers to the mapping between a key and an implementation as a Binding. An implementation can consist of a single object, a class which Guice should also inject, or a custom provider.
どのようにしてGuiceは「何をインジェクトするか」を認識しているのでしょう?まず第一に、Typeやオプショナルアノテーションによって構成されるKeyが、依存性を一意に特定します。GuiceではKeyキーと実装とのマッピングをBindingと呼びます。実装は単一のオブジェクト、およびGuiceが注入するべきクラス、またはカスタムプロバイダーから成ることができます。
When injecting a dependency, Guice first looks for an explicit binding, a binding which you specified using the Binder. The Binder API uses the builder pattern to create a domain-specific expression language. Different methods return different objects depending on the context limiting you to appropriate methods.
依存性を注入するときGuiceは開発者がBinderを使って指定した明示的なバインディングを初めに探します。BinderのAPIは、ドメイン特有の式言語を作るためにビルダーパターンを使います。異なるメソッドは、適切なメソッドに制限するためのコンテキストによって、異なるオブジェクトを返します。
For example, to bind an interface Service to a concrete implementation ServiceImpl, call:
たとえば、Serviceインターフェイスを具体的な実装であるServiceImplとバインドするためには、以下のように呼び出します。
binder.bind(Service.class).to(ServiceImpl.class);
This binding matches the following the method:
このバインディングは、以下のメソッドに一致します。
@Inject void injectService(Service service) { ... }
Note: In contrast to some other frameworks, Guice gives no special treatment to "setter" methods. Guice will inject any method with any number of parameters so long as the method has an @Inject annotation, even if the method is in a superclass.
注記:他のフレームワークと比べると、GuiceはSetterメソッドを特別扱いしません。Guiceは、いくつかの引数を持つような、どんなメソッドであろうとも@Injectアノ手―ションを持つ限りは、インジェクトすることができます。たとえ、スーパークラスのメソッドであってもインジェクトできます。