Injector 通過檢查 bindings 定義來創(chuàng)建某個類型的實例對象。定義在 Module 中的綁定稱為“明確聲明綁定(Explicit bindings”。Injector 會首先使用帶有 Explicit Bindings 為某個類型創(chuàng)建實例對象。 當(dāng)?shù)硞€類型沒有明確定義綁定時,Injector 試圖構(gòu)造“即時綁定 (Just-in-time Bindings),JIT Bindings 也成為隱含綁定 (implicit bindings).
Injector 通過使用類的 injectable constructor 來創(chuàng)建該類的實例對象。injectable constructor 可以為該類定義的 public 不帶參數(shù)的構(gòu)造函數(shù)或是帶有 @Injector 標(biāo)記的構(gòu)造函數(shù)。
比如 Android RoboGuice 使用指南(4):Linked Bindings 中 MyRectangle 的無參數(shù)構(gòu)造函數(shù):
public class MyRectangle extends Rectangle{
public MyRectangle(){
super(50,50,100,120);
}
...
}
和 Android RoboGuice 使用指南(6):Instance Bindings 定義的含 @Injector 標(biāo)記的構(gòu)造函數(shù):
public class MySquare extends MyRectangle {
@Inject public MySquare(@Named("width") int width){
super(width,width);
}
}
該標(biāo)記通知 Injector 某個類型的缺省實現(xiàn),其功能和 Linked Bindings 類似,例如:
@ImplementedBy(PayPalCreditCardProcessor.class)
public interface CreditCardProcessor {
ChargeResult charge(String amount, CreditCard creditCard)
throws UnreachableException; }
和
bind(CreditCardProcessor.class)
.to(PayPalCreditCardProcessor.class);
等效。 如果某個類型同時含有 @ImplementedBy 和 bind 定義,將優(yōu)先使用 bind 中的定義。
注: @ImplementedBy 定義了從 Interface 到實現(xiàn)的依賴,一般不建議使用。
@ProvidedBy 通知 Injector 某個類型使用那個缺省 Provider 來創(chuàng)建實例對象,例如:
@ProvidedBy(DatabaseTransactionLogProvider.class)
public interface TransactionLog {
void logConnectException(UnreachableException e);
void logChargeResult(ChargeResult result);
}
和下面 Binding 等效:
bind(TransactionLog.class)
.toProvider(DatabaseTransactionLogProvider.class);
和 @ImplementedBy 一樣,如果同時定義了 @ProvidedBy 和 bind,模塊中定義的 bind 優(yōu)先