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


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