Reputation: 1579
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
Reputation: 16390
There are three different reasons you might want to inject a Provider<T>
instead of just injecting T
(see Guice's documentation):
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).get()
method is called, which is decided by your code.User
object.Upvotes: 18