You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dagger2中如何通过@Named注入同类不同构造参数的两个实例

实现步骤和注意事项

你编写的Module配置本身已经符合要求,只需要按照以下操作即可完成两个不同构造参数实例的注入:

  1. 确认Component正确关联Module
    确保你的AppComponent已经将AppModule加入模块配置,示例如下:
@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
    fun inject(activity: MainActivity)
}
  1. 注入侧保持原有注解配置即可
    在MainActivity中直接沿用你之前的注入写法即可,注意Kotlin场景下必须使用@field:Named才能将注解作用到成员字段上,否则会导致注入失效:
@Inject
@field:Named("Id1")
lateinit var rect1: Shape

@Inject
@field:Named("Id2")
lateinit var rect2: Shape
  1. 验证注入结果
    完成Component的注入调用后,调用两个实例的info()方法即可验证:
  • rect1.info() 会打印日志输出id为ABC
  • rect2.info() 会打印日志输出id为XYZ

可选扩展:直接注入Rectangle实例

如果你需要直接注入Rectangle类型而不是Shape接口,只需要修改Module中两个Shape提供方法的返回值类型即可:

@Provides
@Named("Id1")
fun provideId1(@Named("id1") id: String): Rectangle {
    return Rectangle(id)
}

@Provides
@Named("Id2")
fun provideId2(@Named("id2") id: String): Rectangle {
    return Rectangle(id)
}

之后注入侧就可以直接声明类型为Rectangle:

@Inject
@field:Named("Id1")
lateinit var rect1: Rectangle

内容的提问来源于stack exchange,提问作者GigaCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:18:04