We may encounter some situations where it's not convenient to obtain a contextual instance through injection, which are as follows:
Either the bean type or qualifiers of an injection point may vary at runtime
In some deployments, there may be no bean that satisfies the bean type and qualifiers of an injection point
We want to loop through all the beans of a specific bean type
For these situations we obtain an instance of Instance
parameterized to the bean type we require:
@Inject Instance<BookSearch> bookSearch;
To retrieve a contextual instance:
BookSearch search = bookSearch.get();
We can also alter the bean types that will be retrieved from Instance
by adding qualifiers either to the injection point or passing them to select()
.
Specifying qualifiers at the injection is simple:
@Inject @Book(Category.NONFICTION) Instance<BookSearch> bookSearch;
But sometimes it's necessary for the qualifiers to be specified dynamically. For us to use dynamic...