我使用 https://guides.codepath.com/android/Dependency-Injection-with-Dagger-2 的 dagger2 演示. 我想使用缓存和非缓存改造调用。我在 NetModule.java 中创建
@Provides @Named("cached")
@Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cache(cache)
.build();
return okHttpClient;
}
@Provides @Named("non_cached")
@Singleton
OkHttpClient provideOkHttpClientNonCached() {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
return okHttpClient;
}
GitHubModule.java 依赖于 NetModule.java。 我的 GitHubComponent.java
@UserScope
@Component(dependencies = NetComponent.class, modules = GitHubModule.class)
public interface GitHubComponent {
void inject(DemoDaggerActivity activity);
}
我的 NetComponent.java
@Singleton
@Component(modules={ApplicationModule.class, NetModule.class})
public interface NetComponent {
// downstream components need these exposed
Retrofit retrofit();
OkHttpClient okHttpClient();
SharedPreferences sharedPreferences();
}
在我的 DemoDaggerActivity.java
中,我注入(inject)了改造:
@Inject @Named("cached")
OkHttpClient mOkHttpClient;
@Inject
Retrofit mRetrofit;
重建项目后出现错误:
我在哪里可以告诉 dagger,我想使用缓存或非缓存改造?
最佳答案
您的 Retrofit 提供者应该为 OkHttpClient 使用 @Named
注释,例如:
@Provides
@Singleton
public Retrofit provideRetrofit(@Named("cached") OkHttpClient okHttpClient)
{
return new Retrofit.Builder()
.baseUrl("...")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
}
关于java - Dagger2 在依赖模块中注入(inject) @Named @Provides 的地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45080227/