我在閱讀this偉大的教程,它解釋了@Component.Builder
如何在Dagger 2中工作。作者做得很好,文章很簡單,但仍然存在一些令我困惑的問題,我需要澄清:匕首2的默認實現看起來是這樣的:瞭解Dagger 2 @Component.Builder註釋
組件:
@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
SharedPreferences getSharedPrefs();
}
模塊:
@Module
public class AppModule {
Application application;
public AppModule(Application application) {
this.application = application;
}
@Provides
Application providesApplication() {
return application;
}
@Provides
@Singleton
public SharedPreferences providePreferences() {
return application.getSharedPreferences(DATA_STORE,
Context.MODE_PRIVATE);
}
}
組件實例化:
DaggerAppComponent appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this)) //this : application
.build();
根據這篇文章,我們可以通過避免將參數傳遞給使用@Component.Builder
和@BindsInstance
註釋模塊構造更加簡化這個代碼,那麼代碼會是這樣的:
成分:
@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
SharedPreferences getSharedPrefs();
@Component.Builder
interface Builder {
AppComponent build();
@BindsInstance Builder application(Application application);
}
}
的米odule:
@Module
public class AppModule {
@Provides
@Singleton
public SharedPreferences providePreferences(
Application application) {
return application.getSharedPreferences(
"store", Context.MODE_PRIVATE);
}
}
和組件實例化:
DaggerAppComponent appComponent = DaggerAppComponent.builder()
.application(this)
.build();
我幾乎不懂上面的代碼是如何工作的,但這裏是我不明白的一部分:我們是如何得到appModule(new AppModule(this))
到application(this)
時我們正在實例化組件?
我希望問題很清楚,謝謝。
如果匕首可以實例無參數模塊本身,我們只是冷冷使用'DaggerAppComponent.builder()建();',還等什麼'申請(這)是爲了? –
檢查你的'Component.Builder'界面!您註冊了一個將應用程序綁定到組件的方法,您必須調用它:'@BindsInstance Builder應用程序(應用程序應用程序);' –
現在我明白了!非常感謝David Medenjak,你非常有幫助 –