Obaid Maroof
Obaid Maroof

Reputation: 1579

Why using Guice Provider instead of normal injection

Sorry for asking dumb question, but I am quite new to Java and Guice framework. I fail to understand the use of Guice Provider class which provides an instance of any class in compression to the normal injected instance. As far as I understand, it allows you to create multiple instances of a class where as Injected instance is always Singleton. Is it the only difference or is there anything more than this?

i.e. difference between:

@Inject SomeClass someObjcet;

VS

@Inject Provider<SomeClass> provider; provider.get();

Upvotes: 5

Views: 5059

Answers (1)

Rog&#233;rio
Rog&#233;rio

Reputation: 16390

There are three different reasons you might want to inject a Provider<T> instead of just injecting T (see Guice's documentation):

  1. Every call to the get() method in a Provider implementation will (usually) return a new instance of the dependency. This would be useful when said instances hold mutable state (otherwise the dependent class, when accessed from multiple threads, could run into concurrency issues).
  2. A provider allows for lazy loading a dependency which is costly to instantiate. With the provider, the object will only be created if and when the get() method is called, which is decided by your code.
  3. A dependent object from a "wider" scope (often a global singleton) can, through the use of a provider, obtain instances of narrower-scoped objects. For example, it could obtain a request-scoped (or session-scoped) User object.

Upvotes: 18

Related Questions