作者:吕兵涛_836 | 来源:互联网 | 2023-01-29 17:50
我使用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 @Named("cached")
OkHttpClient mOkHttpClient;
@Inject
Retrofit mRetrofit;
重建项目后,我收到错误:
![在此输入图像描述](https://img.php1.cn/3cd4a/1eebe/cd5/43a754c811e7ec5c.webp)
我在哪里可以告诉匕首,我想使用缓存或非缓存改造?
1> DeKaNszn..:
您的Retrofit提供程序应该使用@Named
OkHttpClient的注释,例如:
@Provides
@Singleton
public Retrofit provideRetrofit(@Named("cached") OkHttpClient okHttpClient)
{
return new Retrofit.Builder()
.baseUrl("...")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
}