【发布时间】:2017-03-23 13:28:37
【问题描述】:
我正在试验 Dagger 2,我只是在测试一些东西以了解框架。
我有一个 ApplicationComponent 需要成为整个应用程序的单例,所以我这样定义它:
@Component(modules = {ApplicationModule.class})
@Singleton
public interface ApplicationComponent {
Context provideContext();
}
带模块:
@Module
public class ApplicationModule {
private Application appContext;
public ApplicationModule(Application appContext) {
this.appContext = appContext;
}
@Provides
@Singleton
public Context provideContext() {
return appContext;
}
}
现在我还想要一个只要应用程序存在就必须存在的 NetworkComponent。 该网络组件需要依赖于 ApplicationComponent。 所以我的网络组件如下:
@Component(dependencies = {ApplicationComponent.class}, modules = {NetworkModule.class})
@PerApp
public interface NetworkComponent extends ApplicationComponent {
@Named(DaggerConstants.DEFAULT_RETROFIT)
Retrofit provideDefault();
@Named(DaggerConstants.OTHER_RETROFIT)
Retrofit provideOther();
void inject(MainActivity activity);
}
模块:
@Module
public class NetworkModule {
@Named(DaggerConstants.DEFAULT_RETROFIT)
@PerApp
@Provides
Retrofit provideDefaultRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.someurl.com/")
.build();
return retrofit;
}
@Named(DaggerConstants.OTHER_RETROFIT)
@PerApp
@Provides
Retrofit provideOtherRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.someotherurl.com/")
.build();
return retrofit;
}
@PerApp
@Provides
SharedPreferences networkPreferences(Context context) {
return context.getSharedPreferences("network", Context.MODE_PRIVATE);
}
}
我有一些问题:
1) 我将这两个组件存储在 Android 的应用程序中。 但对我来说,我存储 AppComponent 和 NetworkComponent 似乎很奇怪。 我的 ApplicationComponent 应该提供 NetworkComponent 不是更好吗?
2) @PerApp 注释和其他东西是否意味着什么,或者 Dagger 只是在寻找一个具有 @PerApp 注释的对象,如果没有,那么它会删除它?我不清楚。
3) 用例如@Singleton 标记模块是否有用,因为这是可能的,但我在任何示例中都看不到。
【问题讨论】:
标签: java android dependency-injection dagger-2 dagger