Java 科特林匕首改造现场注入
当尝试使用dagger注入字段变量时,我得到了null。这是文件。有些是Java语言,有些是Kotlin语言 App.javaJava 科特林匕首改造现场注入,java,android,kotlin,dagger-2,Java,Android,Kotlin,Dagger 2,当尝试使用dagger注入字段变量时,我得到了null。这是文件。有些是Java语言,有些是Kotlin语言 App.java public class App extends DaggerApplication{ @Override protected AndroidInjector<? extends DaggerApplication> applicationInjector() { return DaggerAppComponent.
public class App extends DaggerApplication{
@Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
return DaggerAppComponent.builder().application(this).build();
}
}
//应在其中执行注入的存储库
class Repository {
private var examsService: BlogExamsService
@Inject
var retrofit: Retrofit? = null
init {
// retrofit is null here
examsService = retrofit?.create(BlogExamsService::class.java)!!
}
}
将
存储库更改为:
class Repository {
private var examsService: BlogExamsService
@Inject
constructor(retrofit: Retrofit) {
examsService = retrofit.create(BlogExamsService::class.java)!!
}
}
将存储库更改为:
class Repository {
private var examsService: BlogExamsService
@Inject
constructor(retrofit: Retrofit) {
examsService = retrofit.create(BlogExamsService::class.java)!!
}
}
字段注入无法工作,因为您没有运行inject()
方法
要使其与您的方法配合使用,您应该调用存储库类:
App.self.getComponent().inject(this)
其中:
self
是应用程序的静态
实例
getComponent()
ApplicationComponent的公共getter
虽然我不建议您使用它,但这是对DI框架的滥用。
您应该创建RepositoryModule
和@提供存储库的实例
,与使用NetworkModule
所做的相同 字段注入无法工作,因为您没有运行inject()
方法
要使其与您的方法配合使用,您应该调用存储库类:
App.self.getComponent().inject(this)
其中:
self
是应用程序的静态
实例
getComponent()
ApplicationComponent的公共getter
虽然我不建议您使用它,但这是对DI框架的滥用。
您应该创建RepositoryModule
和@提供存储库的实例
,与使用NetworkModule
所做的相同 您没有注入存储库
,您可以将其作为依赖关系图的一部分并从模块中提供。您没有注入存储库
,您可以将其作为依赖关系图的一部分并从模块中提供。我正在代码中的其他地方创建存储库实例。知道为什么字段注入不起作用吗?不要自己创建实例,使用@inject internal lateinit var repository:repository
注入它。我正在代码中的其他地方创建存储库的实例。知道为什么字段注入不起作用吗?不要自己创建实例,使用@inject internal lateinit var repository:repository
class Repository {
private var examsService: BlogExamsService
@Inject
constructor(retrofit: Retrofit) {
examsService = retrofit.create(BlogExamsService::class.java)!!
}
}