eur*_*com 4 java android dependency-injection dagger dagger-2
我使用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;
}
Run Code Online (Sandbox Code Playgroud)
GitHubModule.java依赖于NetModule.java.我的GitHubComponent.java
@UserScope
@Component(dependencies = NetComponent.class, modules = GitHubModule.class)
public interface GitHubComponent {
void inject(DemoDaggerActivity activity);
}
Run Code Online (Sandbox Code Playgroud)
我的NetComponent.java
@Singleton
@Component(modules={ApplicationModule.class, NetModule.class})
public interface NetComponent {
// downstream components need these exposed
Retrofit retrofit();
OkHttpClient okHttpClient();
SharedPreferences sharedPreferences();
}
Run Code Online (Sandbox Code Playgroud)
在我的DemoDaggerActivity.java注入改造中:
@Inject @Named("cached")
OkHttpClient mOkHttpClient;
@Inject
Retrofit mRetrofit;
Run Code Online (Sandbox Code Playgroud)
重建项目后,我收到错误:
我在哪里可以告诉匕首,我想使用缓存或非缓存改造?
您的Retrofit提供程序应该使用@NamedOkHttpClient的注释,例如:
@Provides
@Singleton
public Retrofit provideRetrofit(@Named("cached") OkHttpClient okHttpClient)
{
return new Retrofit.Builder()
.baseUrl("...")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4615 次 |
| 最近记录: |