我正在用Kotlin和Dagger 2开发一个Android项目。我有一个MyModule
,其中定义了一些提供程序功能。
@Module
object MyModule {
@Provides
@JvmStatic
internal fun provideSomething(): Something {
...
}
}
在我的Foo
类中,我将Something
作为成员变量注入:
class Foo(@Inject val something: Something) {
}
但是现在我想让这个Foo
类也可以注入到另一个类中,例如在名为Bar
的类中:
class Bar(@Inject val foo: Foo)
如何实现?如果使用Java,我可以做:
class Foo {
// I inject something
@Inject
private Something something;
// I also make Foo to be injectable to other class
@Inject
public Foo()
}
但是如何在我的Kotlin Foo
类中实现相同?
在Kotlin中,您必须这样做:
class Foo @Inject constructor(val something: Something) {
}
我不确定是否也可以使用相同的名称。
假设Something
是您创建的类。您甚至不需要提供@Module
。
您可以这样做,
class Something @Inject constructor() {
}
您只需将@Inject添加到Something
构造函数中,就是这样,Dagger知道如何提供它。然后在您的Foo
类中>
class Foo @Inject constructor() { @Inject lateinit var something: Something }
完成,如果您拥有
Something
类,则不需要@Module和@Component。
但是
如果类Something
不在您的控制之下,那么我们需要走很长的路,例如,
步骤1:创建模块
@Module object MyModule { @Provides @JvmStatic internal fun provideSomething(): Something { ... } }
第2步:定义组件
@Component(modules = [MyModule::class]) interface MyComponent { fun inject(foo: Foo) //mention the place where you need to inject variables }
第3步:启动组件
class Foo @Inject constructor(){ @Inject lateinit var something:Something init{ DaggerMyComponent().create().inject(this) //do this before using `something` or else face `UninitializedPropertyException` //You can now freely use `something`, **Dagger** has already performed his magic } }
更新:
假设Something
具有参数化的构造函数,看起来像这样,class Something @Inject constructor(mRandom : RandomClass)
,再次出现两种可能性
如果您拥有RandomClass
,您可以像这样将[InC]构造函数添加@Inject,
将在需要的地方提供RandomClass
就是这样,Dagger
class RandomClass @Inject constructor(){
}
。并且如果RandomClass
不在您的控制之下,则需要使用这样的RandomClass
来提供它,
@Module
将此
@Module object RandomModule { @JvmStatic @Provides fun providesRandomClass(): RandomClass { ... } }
添加到您的@Module
并在需要依赖项的任何地方启动@Component
(示例已在上面的步骤中提供]]。
故事的寓意是,一种或另一种匕首应该知道如何提供 @Component
对于您的特定示例,假设我们有
RandomClass
只需告诉匕首
如何提供class Something @Inject constructor(mString:String,customType:CustomType){ }
和String
CustomType
然后是对
@Module object CustomModule { @JvmStatic @Provides @Named("AnyName") //Just to differentiate which string we need fun providesString() = "AnyName" @JvmStatic @Provides fun providesCustomType(): CustomType { ... } }
构造函数的最后一点修改,Something