我使用https://guides.codepath.com/android/Dependency-Injection-with-Dagger-2的dagger2演示。
我想使用缓存和non_cached改造电话。我在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;

重建项目后,我得到错误:

java - Dagger2在依赖模块中注入(inject)@Named @Provides的地方?-LMLPHP

我在哪里可以告诉 Dagger ,我要使用缓存还是非缓存改造?

最佳答案

您的Retrofit提供程序应为OkHttpClient使用@Named批注,例如:

@Provides
@Singleton
public Retrofit provideRetrofit(@Named("cached") OkHttpClient okHttpClient)
{
    return new Retrofit.Builder()
            .baseUrl("...")
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();
}

09-26 23:43
查看更多