【七】注入框架RoboGuice使用:(Your First Custom Binding)

           上一篇我们简单的介绍了一下RoboGuice的使用(【六】注入框架RoboGuice使用:(Singletons And ContextSingletons)),今天我们来看下自定义绑定(binding)。

           (一):使用自定义绑定,我们可以绑定一个类或者一个接口到一个子类,实例或者内容提供者(provinders).

         现在我们假设:

public interface IFoo {}

public class Foo implements IFoo {}
         该自定义绑定允许绑定一个接口IFoo到类Foo中,然后每一个注解(@Inject IFoo),就会创建一个Foo的实例。

public class MyActivity extends RoboActivity {
    //How to tell RoboGuice to inject an instance of Foo ?
    @Inject IFoo foo;
}
      (二):定义自定义绑定:

      进行自定义绑定,我们需要创建自己的module(s),从RoboGuice 2.0版本开始Modules变得很容易创建。   

           ①:在Androidmanifset.xml中注册Modules

           ②:创建继承AbstractModule的类


      2.1:在Androidmanifset.xml中注册Modules

             在Androidmanifset.xml中,application标签中添加一些meta-data标签字段以及modules全名,如下所示:

<application ...>
    <meta-data android:name="roboguice.modules"
               android:value="com.example.MyModule,com.example.MyModule2" />                
</application>
      2.2: 创建继承AbstractModule的类

          每一个modules必须在创建之前必须要注册,这些全部会通过反射进行访问。看下面的实例代码:

package com.example;

public class MyModule extends AbstractModule { 
    //a default constructor is fine for a Module

    public void bind() {
        bind(IFoo.class).to(Foo.class);
    }
}

public class MyModule2 extends AbstractModule {
    //if your module requires a context, add a constructor that will be passed a context.
    private Context context;

    //with RoboGuice 3.0, the constructor for AbstractModule will use an `Application`, not a `Context`
    public MyModule( Context context ) {
        this.context = context;
    }

    public void bind() {
        bind(IFoo.class).toInstance( new Foo(context));
    }
}


           

           

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值