Dagger2: @Qualifier is used to distinguish between objects of the same type but with different instances
Copied from https://blog.mindorks.com/introduction-to-dagger-2-using-dependency-injection-in-android-part-2-b55857911bcd
@Qualifier
annotation is provided by javax.inject
package and is used to qualify the dependency. For example, a class can ask both, an Application Context
and an Activity Context
. But both these Objects will be of type Context
. So, for Dagger2 to figure out which variable is to be provided with what, we have to explicitly specify the identifier for it.
Thus @Qualifier
is used to distinguish between objects of the same type but with different instances.
Copied from https://zhuanlan.zhihu.com/p/24454466
我们在使用@Module来标注提供依赖的方法时,方法名可以随便定义的(虽然我们定义方法名一般以provide开头,但这并不是强制的,只是为了增加可读性而已)。那么Dagger2怎么知道这个方法是为谁提供依赖呢?答案就是返回值的类型,Dagger2根据返回值的类型来决定为哪个被@Inject标记了的变量赋值。但是问题来了,一旦有多个一样的返回类型Dagger2就懵逼了。@Qulifier的存在正式为了解决这个问题,我们使用@Qulifier来定义自己的注解,然后通过自定义的注解去标注提供依赖的方法和依赖需求方(也就是被@Inject标注的变量),这样Dagger2就知道为谁提供依赖了。----一个更为精简的定义:当类型不足以鉴别一个依赖的时候,我们就可以使用这个注解标示。