上一篇我们简单的介绍了一下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));
}
}