@Named注释异常

时间:2018-01-23 13:46:18

标签: android kotlin dagger-2

我在Dagger 2 @Named Kotlin注释中获得了构建异常(Java使用相同的代码正常工作)

Error:[dagger.android.AndroidInjector.inject(T)] @javax.inject.Named("LOGGING_INTERCEPTOR") okhttp3.Interceptor cannot be provided without an @Provides-annotated method.

以下是我的API模块代码的一部分:

  @Provides
  @Named(LOGGING_INTERCEPTOR)
  fun provideLoggingInterceptor() = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }

  @Provides
  @Named(CONNECTIVITY_INTERCEPTOR)
  fun provideConnectivityInterceptor(): Interceptor = ConnectivityInterceptor()

  @Singleton
  @Provides
  fun provideOkHttpClient(
      @Named(CONNECTIVITY_INTERCEPTOR) connectivityInterceptor: Interceptor,
      @Named(LOGGING_INTERCEPTOR) loggingInterceptor: Interceptor
  ): OkHttpClient = OkHttpClient.Builder()
    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
    .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
    .addInterceptor(connectivityInterceptor)
    .apply { if (BuildConfig.DEBUG) addInterceptor(loggingInterceptor) }
    .build()

有人可以解释一下为什么会发生这种情况以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您必须提供以下依赖项:

@Provides
@Named(LOGGING_INTERCEPTOR)
fun provideLoggingInterceptor(): Interceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }

这里的问题是您实际提供HttpLogginInterceptor而不是Interceptor(对于Dagger)。您必须明确指定返回类型。