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