系列文章目录
前言
dagger2作为google出的依赖注入框架,在编译时生成依赖注入代码,较square的dagger在运行期反射获取注解内容在运行效率上有了较大的提升。dagger2相对而言学习成本较高,但在解耦较高尤其与mvp的结合使用,还是给项目带来很大的好处。相信有很多的开发者都蠢蠢欲动。关于dagger2原理介绍的文章也有很多,本文主要介绍一下在使用过程中比较常见的一个错误,希望能够帮助大家从错误中更深刻掌握dagger2的一些原理。
提示:以下是本篇文章正文内容,下面案例可供参考
一、报错是什么原因先看log?
符号: 类 DaggerBaseActivityComponent
位置: 程序包 com.example.dingdongoa.di.component
/Users/qiji/Desktop/AndroidProject/wangshidecheng/oa-anfang/app/src/main/java/com/example/dingdongoa/di/component/BaseActivityComponent.java:52: 错误: [Dagger/MissingBinding] com.example.dingdongoa.mvp.presenter.activity.information.staff.UserStaffPresenter cannot be provided without an @Inject constructor or an @Provides-annotated method.
public interface BaseActivityComponent { //设置文件组成关联,有几个需要的Activity添加几个
^
com.example.dingdongoa.mvp.presenter.activity.information.staff.UserStaffPresenter is injected at
com.example.dingdongoa.base.BaseMVPActivity.mPresenter
com.example.dingdongoa.activity.information.staff.UserStaffActivity is injected at
com.example.dingdongoa.di.component.BaseActivityComponent.injectUserStaffActivity(com.example.dingdongoa.activity.information.staff.UserStaffActivity)
注: 某些输入文件使用或覆盖了已过时的 API。
注: 有关详细信息, 请使用 -Xlint:deprecation 重新编译。
43 个错误
二、解决方案
1.首先检查为什么BaseActivityComponent类activity没有找到,看看是否有写对应activity
代码如下(示例):
@ActivityScope
@Component(dependencies = AppComponent.class, modules = BaseActivityModule.class)
public interface BaseActivityComponent { //设置文件组成关联,有几个需要的Activity添加几个
void injectMainActivity(MainActivity activity);
void injectLoginActivity(LoginActivity activity);
void injectWelcomeActivity(WelcomeActivity activity);
void injectZxingOAActivity(ZxingOAActivity activity);
}
2.查看RxPresenter类中是否通过@Inject注解其构造函数,如下
代码如下(示例):
很明显缺少@Inject注解
总结
逻辑如下:
1. UserStaffPresenter方法会先去判断该module中是否有提供UserStaffPresenter实例对象的方法,有则成功返回结束。
2. 如果没有,会再去RxPresenter类中查找是否有带@Inject标记的构造方法,如果有则成功返回结束。
3.如果也没有,那么就会报这个错误了。