Dagger2在依赖模块中注入@Named @Provides?

时间:2017-07-13 12:10:47

标签: java android dependency-injection dagger-2 dagger

我使用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;

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

enter image description here

我在哪里可以告诉匕首,我想使用缓存或非缓存改造?

3 个答案:

答案 0 :(得分:6)

您的Retrofit提供商应该为OkHttpClient使用@Named注释,例如:

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

答案 1 :(得分:2)

您有两个同名的方法:provideOkHttpClient()。重命名其中一个,使它们区别开来。

答案 2 :(得分:1)

如果您使用的是kotlin,则正确的注入named的方法是下一个:

@field:[Inject Named("api1")]

来源:https://medium.com/@WindRider/correct-usage-of-dagger-2-named-annotation-in-kotlin-8ab17ced6928