dagger2 库的引入
dependencies {
implementation 'com.google.dagger:dagger:2.19'
annotationProcessor 'com.google.dagger:dagger-compiler:2.19'
}

创建一个类Person,如果需要在多个不同的地方使用Person对象,那么需要再不同地方的创建,这都不是问题,但是如果想在创建person对象的时候添加属性,那么这就尴尬了,需要在每个地方都添加,这里先不说修改 ,先说使用.
正常的使用:

获取的结果:

使用dagger2 ,获取创建对象


获取的结果:

有点坑吧,使用dagger2后,获取的竟然是空对象吧。事实是在我们用inject注入对象后,就已经发上变化了,在android studio种重新rebuild 下项目,发现在 app->build->source->apt-debug->包名下面自动生成2个文件。

现在我们要做的是将2个自动生成的类关联起来,前面获取对象为null, 是因为acitivity和person没有关联关系。
自动生成的俩个类分别是:


没有关系,怎么办,建立关系呗,这时候需要moudle,和compoent,这俩个注解了.


这俩个注解有什么用,其实就相当于桥梁,将activity和person对象关联起来了。后面分析时候会指出,
这个时候我们还需要重新rebuild下,发现又自动生成一个文件了。

里面的内容为:

这时我们需要在我们的页面和对象关联起来

这个时候我们再调用:

获取的对象不为null了。
分析整个流程。
关键是
DaggerPersonCompnent.builder().personModule(new PersonModule(this)).build().inject(this);
这句。
最主要是这句,

通过向上转型:

提供一个Person对象的入口。
再通过同一个对象的方法,将activity和person对象关联

具体的实现
@Override
public void injectMembers(MainActivity instance) {
if (instance == null) {
throw new NullPointerException("Cannot inject members into a null reference");
}
instance.person = personProvider.get();
}
再看另一种情况
去掉Person中的注入,在PersonModule中加入注入


重新rebuild

前面的类似:

主要这俩个方法,
mainActivityMembersInjector.injectMembers(mainActivity);
具体的实现

personProvider就是
this.getProvidesProvider = PersonModule_GetProvidesFactory.create(builder.personModule);
具体的实现是:

这样就关联起来了。
网友评论