【七】注入框架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变得非常easy创建。   

           ①:在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));
    }
}


           

           

版权声明:本文博客原创文章。博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/bhlsheji/p/4638630.html