その場バインディング
インジェクタがあるタイプのインスタンスを必要とするとき、バインディングを必要とする。 モジュールで定義されたバインディングのことを明示的バインディングと呼び、インジェクタはそれが提供されている場合はそれを使う。 タイプ(のインスタンス)が必要にも関わらず明示的バインディングが無い場合には、インジェクタは「その場バインディング」を試みる。 これらは、JITバインディングとか暗黙的バインディングなどとも呼ばれる。
コンストラクタバインディング
Guiceは、そのタイプの注入可能なコンストラクタを使うことにより、コンクリートな型に対するバインディングを作成する。 これらは、publicで引数なしのコンストラクタか、@Injectアノテーションのついたコンストラクタである。
public class PayPalCreditCardProcessor implements CreditCardProcessor { private final String apiKey; @Inject public PayPalCreditCardProcessor(@Named("PayPal API key") String apiKey) { this.apiKey = apiKey; }
Guice will not construct nested classes unless they have the static modifier. Inner classes have an implicit reference to their enclosing class that cannot be injected.
@ImplementedBy
Annotate types tell the injector what their default implementation type is. The @ImplementedBy annotation acts like a linked binding, specifying the subtype to use when building a type.
@ImplementedBy(PayPalCreditCardProcessor.class) public interface CreditCardProcessor {
ChargeResult charge(String amount, CreditCard creditCard)
throws UnreachableException;
}
The above annotation is equivalent to the following bind() statement:
bind(CreditCardProcessor.class).to(PayPalCreditCardProcessor.class);
If a type is in both a bind() statement (as the first argument) and has the @ImplementedBy annotation, the bind() statement is used. The annotation suggests a default implementation that can be overridden with a binding. Use @ImplementedBy carefully; it adds a compile-time dependency from the interface to its implementation.
@ProvidedBy
@ProvidedBy tells the injector about a Provider class that produces instances:
@ProvidedBy(DatabaseTransactionLogProvider.class) public interface TransactionLog {
void logConnectException(UnreachableException e); void logChargeResult(ChargeResult result);
}
The annotation is equivalent to a toProvider() binding:
bind(TransactionLog.class)
toProvider(DatabaseTransactionLogProvider.class);
Like @ImplementedBy, if the type is annotated and used in a bind() statement, the bind() statement will be used.