Dagger2 知识梳理(1) Dagger2 依赖注入的两种方式

1、资料推荐

最近这几天一直在看有关Dagger2有关的文章,感受就是这东西真难用、真难懂,数次想要放弃,还好有网上大神的教程帮助,模模糊糊总算能把基本的几个概念跑通了。html

这里首先推荐 牛晓伟 的下面一系列文章,其将Dagger2的基本思想讲的通俗易懂:java

接下来是结合具体例子进行分析的两篇文章,适合在理解基本思想的前提下对Dagger2有个更直观的认识:android

还有前同事 Johnny ShiehDagger2系列,里面提到了后来新增的一些用法:git

了解完以上这些基础文章,就能够尝试去啃一下官方的英文文档了,里面介绍了如何在Android中使用Dagger2,可是不得不说,写的真是晦涩难懂,网上找了好久,也没有把AndroidInjector说明白的:github

虽然网上的例子不少,可是咱们花了那么多时间去看这些文章,本质上仍是要用到项目中,这里确定要优先推荐Google的官方架构Demotodo-mvp-dagger2,这里面涉及到了不少新的注解用法。网络

2、导入依赖

在导入依赖的时候,须要考虑当前工程中使用的Gradle插件的版本。若是当前的插件版本小于2.2,那么须要引入 android-apt 插件,Dagger2 入门,以初学者角度 中就是用的这种方式。架构

在示例代码中,根目录下的build.gradle文件配置的Gradle插件版本为2.3.3app

由于大于 2.2,因此我只须要在 app模块中的 build.gradle文件中,引入如下两个依赖就行了:

3、依赖注入的两种方式

下面,咱们用一个简单的例子来演示使用Dagger2完成依赖注入的两种方式:在进行数据的读写时,咱们能够经过数据管理者DataRepository来管理数据源,外部经过调用这个数据仓库提供的方法来读写数据,完整的源码能够查看 Dagger2Sample 中第一章。框架

对于这些数据源的赋值,就能够采用依赖注入的方式来实现。ide

  • DataRepository:目标类。
  • DataRepository内部的数据源:目标依赖类。

3.1 在目标依赖类构造函数上使用 @Inject

咱们先看第一种方法,经过“在目标依赖类构造函数上使用@Inject,来完成依赖注入”。

第一步

先建立一个LocalSource表示本地的数据源,并在它构造函数上加上@Inject注解。这样Dagger2在尝试建立一个LocalSource对象赋值给DataRepository中的mLocalSource变量时,就会调用这个构造函数。

public class LocalSource {

    @Inject
    public LocalSource() {}

    public String getData() {
        return "使用在构造函数上使用 @Inject 的方式,获取到了本地数据";
    }
}
复制代码

第二步

接下来须要声明一个用@Component注解的接口或者抽象类,用于注入依赖,这个接口的方法名能够为任意值,可是其形参必须是目标类的具体类型,而返回值只能为void或者目标类的具体类型。

@Component
public interface SourceComponent {
    public void inject(DataRepository dataRepository);
}
复制代码

第三步

作好前期这些准备,接下来须要按顺序进行如下几步操做:

  • 在目标类中须要被注入的变量上加上@Inject注解。
  • make一下工程,让Dagger2根据SourceComponent中声明的接口建立一个DaggerSourceComponent实现类。
  • 在须要注入的时候调用DaggerSourceComponent.create().inject(this)方法,完成依赖注入。

DataRepository文件以下所示:

public class DataRepository {

    @Inject
    LocalSource mLocalSource;

    public DataRepository() {
        DaggerSourceComponent.create().inject(this);
    }

    public String getData() {
        return mLocalSource.getData();
    }

}
复制代码

流程以下图所示:

3.2 使用 @Module

3.1的实现方式有一个缺点,就是须要修改构造函数,可是这对于一些第三方的对象来讲是不可能作到的,此时就须要经过另外一种方法来建立对象。

咱们经过下面这个例子来演示:在DataRepository中实例化一个远程数据源RemoteSource

第一步

RemoteSource的构造函数上再也不须要添加@Inject注解:

public class RemoteSource {

    public String getData() {
        return "使用 @Module 的方式,获取到了网络数据";
    }
}
复制代码

第二步

接下来建立一个RemoteSourceModule类,用于提供RemoteSource对象。Dagger2会根据它声明的方法的返回值类型去识别提供的是哪一种类型的对象,这里有两点须要注意:

  • Module类须要加上@Module注解
  • 提供RemoteSource的方法须要加上@Provides注解
@Module
public class RemoteSourceModule {

    @Provides
    public RemoteSource provideRemoteSource() {
        return new RemoteSource();
    }
}
复制代码

第三步

SourceComponent中,咱们须要告诉它哪些Module能够用来建立目标类所依赖的实例,这里和第一种方式的区别就是须要在@Component后面加上用来建立依赖实例的Module类名:

@Component(modules = {RemoteSourceModule.class})
public interface SourceComponent {
    public void inject(DataRepository dataRepository);
}
复制代码

第四步

而在目标类中,RemoteSourceLocalSource同样,都须要加上@Inject注解:

public class DataRepository {

    @Inject
    LocalSource mLocalSource;

    @Inject
    RemoteSource mRemoteSource;

    public DataRepository() {
        DaggerSourceComponent.create().inject(this);
    }

    public String getData() {
        return mLocalSource.getData();
    }

    public String getNetData() {
        return mRemoteSource.getData();
    }
}
复制代码

流程以下图所示:

3.3 Demo 演示

下面,咱们用一个简单的程序来验证DataRepository中的mLocalSource/mRemoteSource是否注入成功:

public class RepositoryActivity extends AppCompatActivity {

    private static final String TAG = RepositoryActivity.class.getSimpleName();
    private Button mBtnGetData;
    private Button mBtnGetNetData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repository);
        mBtnGetData = (Button) findViewById(R.id.bt_get_data);
        mBtnGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DataRepository repository = new DataRepository();
                String data = repository.getData();
                Toast.makeText(RepositoryActivity.this, data, Toast.LENGTH_SHORT).show();
            }
        });
        mBtnGetNetData = (Button) findViewById(R.id.bt_get_net_data);
        mBtnGetNetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DataRepository repository = new DataRepository();
                String data = repository.getNetData();
                Toast.makeText(RepositoryActivity.this, data, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
复制代码

运行结果为:

3.4 依赖注入的过程

下面,咱们来看一下依赖注入的内部实现,整个依赖注入的入口函数为DaggerSourceComponent,在上面的例子中,它的源码为:

public final class DaggerSourceComponent implements SourceComponent {

  private Provider<RemoteSource> provideRemoteSourceProvider;
  private MembersInjector<DataRepository> dataRepositoryMembersInjector;

  private DaggerSourceComponent(Builder builder) {
    assert builder != null;
    initialize(builder);
  }

  public static Builder builder() {
    return new Builder();
  }

  public static SourceComponent create() {
    return new Builder().build();
  }

  @SuppressWarnings("unchecked")
  private void initialize(final Builder builder) {

    this.provideRemoteSourceProvider =
        RemoteSourceModule_ProvideRemoteSourceFactory.create(builder.remoteSourceModule);

    this.dataRepositoryMembersInjector =
        DataRepository_MembersInjector.create(
            LocalSource_Factory.create(), provideRemoteSourceProvider);
  }

  @Override
  public void inject(DataRepository dataRepository) {
    dataRepositoryMembersInjector.injectMembers(dataRepository);
  }

  public static final class Builder {
    private RemoteSourceModule remoteSourceModule;

    private Builder() {}

    public SourceComponent build() {
      if (remoteSourceModule == null) {
        this.remoteSourceModule = new RemoteSourceModule();
      }
      return new DaggerSourceComponent(this);
    }

    public Builder remoteSourceModule(RemoteSourceModule remoteSourceModule) {
      this.remoteSourceModule = Preconditions.checkNotNull(remoteSourceModule);
      return this;
    }
  }
}
复制代码

当咱们调用静态的create()方法后会返回一个DaggerSourceComponent实例,它是前面声明的SourceComponent的实现类。其内部最关键的成员变量是DataRepository_MembersInjector类,它是依赖注入的实际执行者,其内部包含了全部须要注入的实例的Provider,这些Provider是在构造时传入的:

当咱们调用DaggerSourceComponentinject方法时,就会去调用DataRepository_MembersInjector类的injectMembers方法,它经过上面这两个Provider所提供的get()方法对目标类中被@Inject注解的成员变量进行赋值:

3.5 依赖查找的过程

对于以上两种依赖注入方法,其前后顺序为:3.2 > 3.1,即Component先会在和它关联的Module中寻找,这些关联的Module包括:

  • 本身声明的Module
  • 依赖的Component所关联的Module
  • 经过@SubComponent继承的Component关联的Module

它会在以上三个维度中寻找Module是否提供了这个类的建立方法(也就是方法的返回值类型为这个类)

  • 若是有,那么就经过该方法建立,例如例子中的RemoteModule
  • 若是没有,那么再经过该类带有@Inject注解标注的构造方法来建立,例如例子中的LocalSource

对于每一个目标依赖类,若是在它的建立过程当中依赖于某个参数,那么就须要先实例化这个参数。这就相似于二叉树遍历的过程,在这一遍历过程当中,若是出现了某个类型不能按照以上两种方式实例化的时候,那么会在编译时抛出异常。


更多文章,欢迎访问个人 Android 知识梳理系列:

相关文章
相关标签/搜索