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

标签 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)了改造:

@Inject @Named("cached")
OkHttpClient mOkHttpClient;

@Inject
Retrofit mRetrofit;

重建项目后出现错误:

enter image description here

我在哪里可以告诉 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/

相关文章:

java - Spring Boot 路由/路径配置

android - 如何为日期选择器设置日期?

java - HERE map API 缺少库错误

android - 导航栏和状态栏不隐藏

android - 如何将 Activity 注入(inject)另一个类(class)

c# - MVVM 光 ViewModelLocator : How to register Singleton ViewModel?

java - Play Framework 2.4 docker镜像运行错误

java - 图片图标 + 图片图标 = 图片图标

java - 当 inputType 为文本时,EditText 接收按键事件,尽管 Dialog.OnKeyListener 消耗了所有事件

java - Android 代码不扫描 BLE 设备 CC2650