Java 声明模块依赖项中命名的的提供方法
我的项目有以下设置Java 声明模块依赖项中命名的的提供方法,java,kotlin,dagger-2,Java,Kotlin,Dagger 2,我的项目有以下设置 @模块 抽象类核心模块{ @提供 @命名(“文本1”) 有趣的textOne()=“text1” @提供 @命名(“文本2”) 有趣的text2()=“text2” } @组件(模块=[CoreModule::class]) 接口核心组件{ @命名(“文本1”) fun textOne():字符串 } @组成部分( 依赖项=[CoreComponent::class] 模块=[AppModule::class] ) 接口AppComponent() @模块() 类AppMod
@模块
抽象类核心模块{
@提供
@命名(“文本1”)
有趣的textOne()=“text1”
@提供
@命名(“文本2”)
有趣的text2()=“text2”
}
@组件(模块=[CoreModule::class])
接口核心组件{
@命名(“文本1”)
fun textOne():字符串
}
@组成部分(
依赖项=[CoreComponent::class]
模块=[AppModule::class]
)
接口AppComponent()
@模块()
类AppModule{
fun getStringDouble(@Named(“text1”)text1:String)=text1+text1
}
这里我有两个组件CoreComponent
,它提供了对AppComponent
的依赖关系。现在我只想向AppComponent
提供text1
因为我在CoreComponent
中添加了@Named(“text1”)
,以指示要向AppComponent
提供的字符串。它迫使我在AppModule中也使用@Named(“text1”)
,这是我不想要的
我如何在
CoreComponent
中创建provision方法,以便只向AppComponent
提供text1,而不必在AppComponent
中的任何地方使用@Named
,最简单的解决方案可能是在不同的键下绑定/提供它,在您的示例中,一个普通的字符串
@Binds // bind it without any qualifier
fun plainText1(@Named("text1") text1: String) : String
如果同一类型有多个值,那么从长远来看,限定符可能更容易使用,因为它们允许正确命名所使用的键 请记住,您也可以创建自己的限定符,而不必使用
@Named
,它只是默认可用
您的设置的另一种选择是使用它,它只允许您在不绑定整个组件依赖项的情况下返回生成的值。您可以从
CoreModule
和CoreComponent
中的Provider方法中删除@Named(“”
)
相反,您可以像这样创建自定义限定符注释
@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
annotation class TextTwoName {
}
并做以下修改
在CoreModule
中,使用texttowname
中的@texttowname
代替@Named(“text2”)
,并从fun textOne()=“text1”中删除@Named(“text1”)
在CoreComponent
中,从fun textOne()中删除@Named(“text1”)
:String
,而name函数name textOne在这里并不重要,只是返回类型重要。它将从CoreModule
如果要公开fun text2()=“text2”
,则可以在CoreComponent
的fun textOne():String
方法中添加@text2name
注释