在模块依赖中声明 named 的提供方法

Declare provision method of named in module dependency

我的项目有以下设置

@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

因为我在CoreComponent中添加了@Named("text1")来表示要提供给AppComponent的字符串。它也迫使我在 AppModule 中使用 @Named("text1"),这是我不想要的。

如何在 CoreComponent 中创建提供方法以仅向 AppComponent 提供 text1,这样我就不必在 [=12] 中到处使用 @Named =]

最简单的解决方案可能是简单地 bind/provide 它在不同的密钥下,在您的示例中是普通的 String

@Binds // bind it without any qualifier
fun plainText1(@Named("text1") text1: String) : String

如果同一类型确实有多个值,那么在长 运行 中使用限定符可能更容易,因为它们允许您正确命名所使用的键。

请记住,您还可以创建您自己的 限定符,而不必使用 @Named,它只是默认可用。


您的设置的另一种选择是使用 (Sub)components for encapsulation,这将允许您只 return 产生的值而不绑定整个组件依赖性。

您可以从 CoreModuleCoreComponent 中的 Provider 方法中删除 @Named("<name>")

相反,您可以像这样创建自定义限定符注释

@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
annotation class TextTwoName {
}

并进行以下更改

CoreModule 中使用 @TextTwoNametextTwo() 中代替 @Named("text2") 并从 fun textOne() = "text1"

中删除 @Named("text1")

CoreComponent 中,从 fun textOne(): String 中删除 @Named("text1") 而名称函数名称 textOne 在这里无关紧要,只有 return 类型很重要。 CoreModule

需要 fun textOne() = "text1"

如果你想公开fun textTwo() = "text2"那么你可以在CoreComponentfun textOne():String方法中添加@TextTwoName注解。