我正在尝试 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:
@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等标记模块是否有用,因为这是可能的,但我在任何示例中都没有看到这一点。