如何解决声明模块依赖中命名的提供方法
我的项目具有以下设置
@Module
abstract class CoreModule {
@Provides
@Named("text1")
fun textOne() = "text1"
@Provides
@Named("text2")
fun textTwo() = "text2"
}
@Component(modules=[CoreModule::class])
interface CoreComponent{
@Named("text1")
fun textOne(): String
}
@Component(
dependencies = [CoreComponent::class]
modules=[AppModule::class]
)
interface AppComponent()
@Module()
class AppModule {
fun getStringDouble(@Named("text1") text1: String) = text1 + text1
}
在这里,我有2个组件CoreComponent
,它们提供对AppComponent
的依赖性。现在,我只想向AppComponent
提供text1。
由于我已经在@Named("text1")
中添加了CoreComponent
来表示要提供给AppComponent
的字符串。这也迫使我在AppModule中也使用@Named("text1")
,这是我不想要的。
如何在CoreComponent
中创建供应方法,以仅向AppComponent
提供text1的方式,而不必在@Named
中的任何地方使用AppComponent
解决方法
最简单的解决方案可能是简单地将其绑定/提供在另一个密钥下,在您的示例中为简单的String
。
@Binds // bind it without any qualifier
fun plainText1(@Named("text1") text1: String) : String
如果您确实有多个相同类型的值,那么从长远来看,使用限定符可能会更容易,因为它们允许您正确命名所使用的键。
请记住,您还可以创建自己的 限定词,而不必使用@Named
,默认情况下它才可用。
设置的一种替代方法是使用here,它将只允许您返回产生的值,而无需绑定整个组件依赖项。
,您可以在@Named("<name>")
和CoreModule
的提供者方法中删除CoreComponent
。
相反,您可以像这样创建自定义的Qualifier批注
@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
annotation class TextTwoName {
}
并进行以下更改
在CoreModule
中,用@TextTwoName
中的textTwo()
代替@Named("text2")
,然后从@Named("text1")
中删除fun textOne() = "text1"
在CoreComponent
中,从@Named("text1")
中删除fun textOne(): String
,而名称函数名称textOne无关紧要,仅返回类型问题。将需要fun textOne() = "text1"
中的CoreModule
如果要公开fun textTwo() = "text2"
,则可以在@TextTwoName
的{{1}}方法中添加CoreComponent
注释。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。