Saturday, February 1, 2014

Utility of javax.inject.Provider

In my previous Custom CDI scopes post I alluded to the utility of the Provider interface but I am continually impressed in how many different situations it can be used in. From the Javadocs :

Compared to injecting T directly, injecting Provider enables:
  • retrieving multiple instances.
  • lazy or optional retrieval of an instance.
  • breaking circular dependencies.
  • abstracting scope so you can look up an instance in a smaller scope from an instance in a containing scope.
Traditionally I have always regarded the first use case, retrieving/creating multiple instances, as the main purpose of the Provider interface. However, the last use case is also quite compelling. For instance, in JSF if one has a ViewScoped managed bean but wants to access a RequestScoped object, say one that uses ThreadLocals per request, one cannot simply inject the RequestScoped object due to the conflicting scopes. Using the Provider interface though a provider can be injected in the ViewScoped bean and then whenever a RequestScoped object is required the provider get method can be used to retrieve the in-scope object. When developing CDI based applications always keep this wildcard in one's back pocket to solve challenging dependency resolution design issues.