2025-02-15

Injector 通過檢查bindings 定義來創建某個類型的實例對象。定義在Module中的綁定稱為“明確聲明綁定(Explicit bindings”。Injector 會首先使用帶有Explicit Bindings為某個類型創建實例對象。 當但某個類型沒有明確定義綁定時,Injector 試圖構造“即時綁定(Just-in-time Bindings),JIT Bindings 也成為隱含綁定(implicit bindings).

Eligible Constructor

Injector 通過使用類的injectable constructor 來創建該類的實例對象。injectable constructor 可以為該類定義的public 不帶參數的構造函數或是帶有@Injector 標記的構造函數。

比如Android RoboGuice 使用指南(4):Linked Bindings/kf/201205/130094.html中MyRectangle的無參數構造函數:

[java] public class MyRectangle extends Rectangle{ 
 public MyRectangle(){ 
 super(50,50,100,120); 
 } 
 … 

public class MyRectangle extends Rectangle{
 public MyRectangle(){
 super(50,50,100,120);
 }
 …
}

和Android RoboGuice 使用指南(6):Instance Bindings/kf/201205/130096.html 定義的含@Injector 標記的構造函數:

[java] public class MySquare extends MyRectangle { 
 @Inject public MySquare(@Named("width") int width){ 
 super(width,width); 
 } 

public class MySquare extends MyRectangle {
 @Inject public MySquare(@Named("width") int width){
 super(width,width);
 }
}

 

[java] @ImplementedBy 
  
該標記通知Injector某個類型的缺省實現,其功能和Linked Bindings 類似,例如: 
@ImplementedBy
 
該標記通知Injector某個類型的缺省實現,其功能和Linked Bindings 類似,例如:
 

 

[java]  @ImplementedBy(PayPalCreditCardProcessor.class) 
public interface CreditCardProcessor { 
 ChargeResult charge(String amount, CreditCard creditCard) 
 throws UnreachableException; } 
@ImplementedBy(PayPalCreditCardProcessor.class)
public interface CreditCardProcessor {
 ChargeResult charge(String amount, CreditCard creditCard)
 throws UnreachableException; }[java] view plaincopyprint?和 

 

[java]  bind(CreditCardProcessor.class) .to(PayPalCreditCardProcessor.class); 
bind(CreditCardProcessor.class) .to(PayPalCreditCardProcessor.class);

 

等效。 如果某個類型同時含有@ImplementedBy 和bind 定義,將優先使用bind 中的定義。

註: @ImplementedBy 定義瞭從Interface到實現的依賴,一般不建議使用。

@ProvidedBy

@ProvidedBy 通知Injector 某個類型使用那個缺省Provider來創建實例對象,例如:

[java]  @ProvidedBy(DatabaseTransactionLogProvider.class) 
public interface TransactionLog { 
 void logConnectException(UnreachableException e); 
 void logChargeResult(ChargeResult result); 

@ProvidedBy(DatabaseTransactionLogProvider.class)
public interface TransactionLog {
 void logConnectException(UnreachableException e);
 void logChargeResult(ChargeResult result);
}
和下面Binding等效:

[java]  bind(TransactionLog.class) 
 .toProvider(DatabaseTransactionLogProvider.class); 
bind(TransactionLog.class)
 .toProvider(DatabaseTransactionLogProvider.class);

 

 和@ImplementedBy 一樣,如果同時定義瞭@ProvidedBy和bind,模塊中定義的bind 優先

 

摘自 引路蜂移動軟件
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *