Dagger 2 constructor injection in kotlin with Named arguments

依然范特西╮ 提交于 2019-12-03 01:18:17

You want to annotate the constructor parameters if you're doing constructor injection, and not the fields - use the @param: annotation target:

@Singleton
class SpiceMix @Inject constructor(@param:Named("oregano") private val oregano: Spice,
                                   @param:Named("sage") private val sage: Spice,
                                   @param:Named("rosemary") private val rosemary: Spice)

Edit: actually, since the resolution order for annotation targets is

  • param;
  • property;
  • field.

according to the docs, having no annotation target should also annotate the parameter of the constructor. So you can just drop the target altogether:

@Singleton
class SpiceMix @Inject constructor(@Named("oregano") private val oregano: Spice,
                                   @Named("sage") private val sage: Spice,
                                   @Named("rosemary") private val rosemary: Spice)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!