Android RoboGuice 使用指南(6):Instance Bindings

jerry Android 2015年08月24日 收藏

我们在前面例子Android RoboGuice 使用指南(4):Linked Bindings 时为简单起见,定义MyRectangle和MySquare时为它们定义了一个不带参数的构造函数,如MyRectangle的如下:

  1. public class MyRectangle extends Rectangle{
  2. public MyRectangle(){
  3. super(50,50,100,120);
  4. }
  5. public MyRectangle(int width, int height){
  6. super(50,50,width,height);
  7. }
  8. }

实际上可以不需要这个不带参数的构造函数,可以使用Instance Bindings ,Instance Bindings可以将一个类型绑定到一个特定的实例对象,通常用于一个本身不依赖其它类的类型,如各种基本类型,比如:

  1. bind(String.class)
  2. .annotatedWith(Names.named("JDBC URL"))
  3. .toInstance("jdbc:mysql://localhost/pizza");
  4. bind(Integer.class)
  5. .annotatedWith(Names.named("login timeout seconds"))
  6. .toInstance(10);

修改MyRectangle和MySquare的定义如下:

  1. public class MySquare extends MyRectangle {
  2. @Inject
  3. public MySquare(@Named("width") int width){
  4. super(width,width);
  5. }
  6. }
  7. ...
  8. public class MyRectangle extends Rectangle{
  9.  
  10. @Inject
  11. public MyRectangle(@Named("width") int width,
  12. @Named("height")int height){
  13. super(50,50,width,height);
  14. }
  15. }

去掉了无参数的构造函数,可以将标注为@Named(“width”)的int 类型绑定到100,添加下面绑定:

  1. bind(Integer.class)
  2. .annotatedWith(Names.named("width"))
  3. .toInstance(100);
  4. bind(Integer.class)
  5. .annotatedWith(Names.named("height"))
  6. .toInstance(120);

运行这个例子,可以得到和前面例子同样的结果。此时使用Injector 构造一个MyRectangle 实例时,Injector自动选用带参数的那个构造函数,使用100,120为width和height注入参数,返回一个MyRectangle对象到需要引用的地方。

尽管可以使用Instance Bindings将一个类型映射到一个复杂类型的类实例,但RoboGuice不建议将Instance Bindings应用到复杂类型的实例,因为这样会使应用程序启动变慢。

正确的方法是使用@Provides 方法,将在下面介绍。

注:GuiceDemo 中的例子没用使用列表的方法来显示所有示例,如需运行所需示例,可以通过Run Configuration->设置Launch 的Activity: