我們在前面例子 Android RoboGuice 使用指南(4):Linked Bindings 時為簡單起見,定義 MyRectangle 和 MySquare 時為它們定義了一個不帶參數(shù)的構造函數(shù),如 MyRectangle 的如下:
public class MyRectangle extends Rectangle{
public MyRectangle(){
super(50,50,100,120);
}
public MyRectangle(int width, int height){
super(50,50,width,height);
}
}
實際上可以不需要這個不帶參數(shù)的構造函數(shù),可以使用 Instance Bindings ,Instance Bindings 可以將一個類型綁定到一個特定的實例對象,通常用于一個本身不依賴其它類的類型,如各種基本類型,比如:
bind(String.class)
.annotatedWith(Names.named("JDBC URL"))
.toInstance("jdbc:mysql://localhost/pizza");
bind(Integer.class)
.annotatedWith(Names.named("login timeout seconds"))
.toInstance(10);
修改MyRectangle和MySquare的定義如下:
public class MySquare extends MyRectangle {
@Inject
public MySquare(@Named("width") int width){
super(width,width);
}
}
...
public class MyRectangle extends Rectangle{
@Inject
public MyRectangle(@Named("width") int width,
@Named("height")int height){
super(50,50,width,height);
}
}
去掉了無參數(shù)的構造函數(shù),可以將標注為 @Named(“width”) 的 int 類型綁定到100,添加下面綁定:
bind(Integer.class)
.annotatedWith(Names.named("width"))
.toInstance(100);
bind(Integer.class)
.annotatedWith(Names.named("height"))
.toInstance(120);
運行這個例子,可以得到和前面例子同樣的結果。此時使用 Injector 構造一個 MyRectangle 實例時,Injector 自動選用帶參數(shù)的那個構造函數(shù),使用100,120為 width 和 height 注入?yún)?shù),返回一個 MyRectangle 對象到需要引用的地方。
盡管可以使用 Instance Bindings 將一個類型映射到一個復雜類型的類實例,但 RoboGuice 不建議將 Instance Bindings 應用到復雜類型的實例,因為這樣會使應用程序啟動變慢。
正確的方法是使用 @Provides 方法,將在下面介紹。
注:GuiceDemo 中的例子沒用使用列表的方法來顯示所有示例,如需運行所需示例,可以通過 Run Configuration-> 設置 Launch 的Activity:
http://wiki.jikexueyuan.com/project/android-roboguice/images/10.png" alt="" />