最近这几天一直在看有关Dagger2
有关的文章,感受就是这东西真难用、真难懂,数次想要放弃,还好有网上大神的教程帮助,模模糊糊总算能把基本的几个概念跑通了。html
这里首先推荐 牛晓伟 的下面一系列文章,其将Dagger2
的基本思想讲的通俗易懂:java
接下来是结合具体例子进行分析的两篇文章,适合在理解基本思想的前提下对Dagger2
有个更直观的认识:android
还有前同事 Johnny Shieh 的Dagger2
系列,里面提到了后来新增的一些用法:git
了解完以上这些基础文章,就能够尝试去啃一下官方的英文文档了,里面介绍了如何在Android
中使用Dagger2
,可是不得不说,写的真是晦涩难懂,网上找了好久,也没有把AndroidInjector
说明白的:github
虽然网上的例子不少,可是咱们花了那么多时间去看这些文章,本质上仍是要用到项目中,这里确定要优先推荐Google
的官方架构Demo
:todo-mvp-dagger2,这里面涉及到了不少新的注解用法。网络
在导入依赖的时候,须要考虑当前工程中使用的Gradle
插件的版本。若是当前的插件版本小于2.2
,那么须要引入 android-apt 插件,Dagger2 入门,以初学者角度 中就是用的这种方式。架构
在示例代码中,根目录下的build.gradle
文件配置的Gradle
插件版本为2.3.3
:app
2.2
,因此我只须要在
app
模块中的
build.gradle
文件中,引入如下两个依赖就行了:
下面,咱们用一个简单的例子来演示使用Dagger2
完成依赖注入的两种方式:在进行数据的读写时,咱们能够经过数据管理者DataRepository
来管理数据源,外部经过调用这个数据仓库提供的方法来读写数据,完整的源码能够查看 Dagger2Sample 中第一章。框架
对于这些数据源的赋值,就能够采用依赖注入的方式来实现。ide
DataRepository
:目标类。DataRepository
内部的数据源:目标依赖类。咱们先看第一种方法,经过“在目标依赖类构造函数上使用@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.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);
}
复制代码
而在目标类中,RemoteSource
和LocalSource
同样,都须要加上@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();
}
}
复制代码
流程以下图所示:
下面,咱们用一个简单的程序来验证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();
}
});
}
}
复制代码
运行结果为:
下面,咱们来看一下依赖注入的内部实现,整个依赖注入的入口函数为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
是在构造时传入的:
当咱们调用DaggerSourceComponent
的inject
方法时,就会去调用DataRepository_MembersInjector
类的injectMembers
方法,它经过上面这两个Provider
所提供的get()
方法对目标类中被@Inject
注解的成员变量进行赋值:
对于以上两种依赖注入方法,其前后顺序为:3.2
> 3.1
,即Component
先会在和它关联的Module
中寻找,这些关联的Module
包括:
Module
Component
所关联的Module
@SubComponent
继承的Component
关联的Module
它会在以上三个维度中寻找Module
是否提供了这个类的建立方法(也就是方法的返回值类型为这个类)
RemoteModule
。@Inject
注解标注的构造方法来建立,例如例子中的LocalSource
。对于每一个目标依赖类,若是在它的建立过程当中依赖于某个参数,那么就须要先实例化这个参数。这就相似于二叉树遍历的过程,在这一遍历过程当中,若是出现了某个类型不能按照以上两种方式实例化的时候,那么会在编译时抛出异常。