Dagger2不能访问为空。 未findjavax.annotation.Nullable
我有一个模块来提供一个Retrofit界面。
@Module class NetModule(val base: String) { @Provides @Singleton fun provideOkHttpClient(): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(object: Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() info("Request for ${request.url()}") return chain.proceed(request) } }).build() } @Provides @Singleton fun provideGson(): Gson { return GsonBuilder() .enableComplexMapKeySerialization() .serializeNulls() .setPrettyPrinting() .setLenient() .create() } @Provides @Singleton fun provideRetrofit(OkHttpClient: OkHttpClient, Gson: Gson): Retrofit { return Retrofit.Builder() .baseUrl(base) .client(OkHttpClient) .addConverterFactory(GsonConverterFactory.create(Gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync()) .build() } @Provides @Singleton fun provideIdService(Retrofit: Retrofit): IdService { return Retrofit.create(IdService::class.java) } }
NetModule
与NetComponent
一起NetComponent
@Singleton @Component(modules = arrayOf(NetModule::class)) interface NetComponent { fun inject(application: Application) fun inject(activity: Activity) }
它被注入到应用程序中并存储在应用程序伴随对象中。
netComponent = DaggerNetComponent.builder().netModule(NetModule("some_url")).build() netComponent.inject(this)
在活动中,我有
@Inject lateinit var idService: IdService
这给出了一个构建错误
如果没有@Provides或@Produces注释方法,则不能提供IdService。
如果我试图注入Retrofit
实例,我得到一个不同的错误
不能访问Nullable
stacktrace显示未findjavax.annotation.Nullable的类文件。
我一直无法find任何引用此错误的东西。 有一个从12小时前的StackOverflowpost似乎有相同的错误,但它已被删除。 https://stackoverflow.com/questions/44983292/cannot-access-nullable-on-injecting-with-dagger2-in-kotlin
我得到了javax.annotation.Nullable未find错误,我可以通过添加包含Nullable注释的findbugs库来修复。
如果您正在使用gradle,请添加以下依赖项:
compile group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.2'
如果没有@Provides或@Produces注释方法,则不能提供IdService。
这是因为您没有在IdService
存在的地方注入依赖IdService
。 所以匕首不知道如何提供IdService
。
NetModule与NetComponent一起使用,它被注入应用程序并存储在应用程序伴随对象中。
你必须在你想要使用它的地方注入依赖项(这里是你的Activity
)
所以在你的Activity的OnCreate
写入注入
netComponent = DaggerNetComponent.builder() .netModule(NetModule("some_url")) .build() .inject(this)