Dagger2 Scope && Qualifier

@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).git

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.github

@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:api

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:app

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

and this the qualifier:ide

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

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

then you can inject the tagged objects:ui

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

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

reference: Dependency injection with Dagger 2 - Custom scopesthis

相關文章
相關標籤/搜索