Dagger2 Scope && Qualifier
博客专区 > lightUp 的博客 > 博客详情
Dagger2 Scope && Qualifier
lightUp 发表于11个月前
Dagger2 Scope && Qualifier
  • 发表于 11个月前
  • 阅读 18
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云实验室 1小时搭建人工智能应用,让技术更容易入门 免费体验 >>>   

@Scope annotation

    @Scope
    public [@interface](https://my.oschina.net/u/996807) ActivityScope {
    
    }

Another part of JSR-330 standard. In Dagger 2 @Scope is used to define custom scopes annotations. In short they make dependencies something very similar to singletons. Annotated dependencies are single-instances but related to component lifecycle (not the whole application).

Now worth-mentioning is that all custom scopes does the same thing (from code perspective) - they keep single instances of objects. But also they are used in graph validation process which is helpful with catching graph structural problems as soon as possible.

@Qualifier

@Qualifier annotation helps us to create “tags” for dependencies which have the same interface. Imagine that you need to provide two RestAdapter objects - one for Github API, another for facebook API. Qualifier will help you to identify the proper one:

Naming dependencies

@Provides
[@Singleton](https://my.oschina.net/u/674)
@RestAdapter("github")  //Qualifier
RestAdapter provideRestAdapter() {
	return new RestAdapter.Builder()
				.setEndpoint("https://api.github.com")
				.build();
}

another:

@Provides
@Singleton
@RestAdapter("facebook")  //Qualifier
RestAdapter provideRestAdapter() {
	return new RestAdapter.Builder()
			.setEndpoint("https://api.facebook.com")
			.build();
}

and this the qualifier:

@Qualifier
@Documented
@Retention(RUNTIME)
public @interface RestAdapter {

	/** The name. */
	String value() default "";
}

then you can inject the tagged objects:

@Inject
@RestAdapter("github")
RestAdapter githubRestAdapter;

@Inject
@RestAdapter("facebook")
RestAdapter facebookRestAdapter;

reference: Dependency injection with Dagger 2 - Custom scopes

共有 人打赏支持
粉丝 11
博文 132
码字总数 287957
×
lightUp
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: