Studio3.0 Dagger2注入方法

该案例是结合MVP模式演示-----------


在app的build.gradle中引入
dependencies {
    compileOnly 'org.glassfish:javax.annotation:10.0-b28'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.5'
    implementation 'com.google.dagger:dagger:2.5'

}

其他什么都不需要,然后在代码中


在主持人LoginPresenterImpl位置使用了注解,并在onCreate方法中

 DaggerLoginComponent.builder().loginModule(new LoginModule(this,new LoginInteractorImpl())).build().inject(this);


在主持人的构造方法上,同样进行了@Inject注解。



并且新建了一个LoginModule类,该类定义了主持人LoginPresenterImpl新建对象所需的参数,并在构造方法中,传递进来,需要在该类上添加@Module注解,同时在下面写了2个方法返回这两个参数,并在方法上进行了@Provides注解,如果需要更多地参数,就需要写对应数量的方法,并且每个方法上都要有@Provides注解。

有个问题是LoginModule类的参数视乎只能是接口,我试过传入实现了LoginInteractor的类LoginInteractorImpl但是提示报错,说该类需要被@Provides注释?



新建了一个LoginComponet接口,该接口定义了一个inject方法,参数是LoginActivity对象,也就是你要用主持人LoginPresenterImpl的activity,并且在该接口上注解@Componet(modules=LoginModule.class),也就是说改接口需要跟LoginModule类一起使用。


当这些注释写好后,在LoginActivity中使用

DaggerLoginComponent.builder().loginModule(new LoginModule(this,new LoginInteractorImpl())).build().inject(this);

来完成present的依赖注入。其中DaggerLoginComponent需要在注解完后在androidStudio的build---make project一下,才能够打出DaggerLoginComponent.该类,该类名字为你新建的接口名,比如我这是LoginComponet,加前缀Dagger,也就是DaggerLoginComponent了。在loginModule方法中需要传入一个LoginModule对象,在inject传入LoginActivity。

具体可以看另外一位写的,我是参考它的配置,不过报错,修改的配置。

代码地址:https://download.csdn.net/download/a2923790861/10334171


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章