我使用 dagger2 演示 https://guides.codepath.com/android/Dependency-Injection-with-Dagger-2。 我想使用缓存和非缓存改造调用。我在 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;
重建项目后出现错误:
我在哪里可以告诉 dagger 我想使用缓存或非缓存改造?
您的 Retrofit 提供商应为 OkHttpClient 使用
@Named
注解,例如:
@Provides
@Singleton
public Retrofit provideRetrofit(@Named("cached") OkHttpClient okHttpClient)
{
return new Retrofit.Builder()
.baseUrl("...")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
}
如果你使用的是kotlin,正确的注入named方法如下:
@field:[Inject Named("api1")]
.
来源:https://medium.com/@WindRider/ Correct-usage-of-dagger-2-named-annotation-in-kotlin-8ab17ced6928
您有两个同名的方法:
provideOkHttpClient()
。重命名其中之一,使它们与众不同。
对于 Kotlin,使用:
@Inject
@field:Named("cached")
lateinit var mOkHttpClient: OkHttpClient
重点关注
@Named
注释,它是使用 Kotlin 中的 @field
注释使用站点目标 指定的。由于旧版本 Dagger 中的 @Target
注释源代码中没有指定 @Named
,因此我们需要告诉 Kotlin 编译器在哪里应用此注释,因此是 @field
使用站点注释目标。源代码中为 FIELD
注解指定了 @Target
@Inject
,因此我们不需要显式地为其指定目标,编译器会自动选择正确的目标
此外,当您有多个注释时,可以将它们组合成类似数组的语法,如下所示:
@field:[Inject Named("cached")]
lateinit var mOkHttpClient: OkHttpClient
为了更彻底的理解,请参阅this。