all
I don't know what's the difference between Inject and Provider in JSR-330.
I am using google guice, and everyday using @Inject, and I know in JSR-330, it has Provider<T>.
My question is
- what's the meaning of
Provider<T>? - when can when user
Provider<T>? - what's the difference with
@Inject?
Thanks in advance.
Everything is already explained into the javadoc, I quote:
Example for #1:
Here you get several instances of
Seatfrom the same provider so it is used as a factory.Example for #2:
Here you use a provider to avoid creating directly the instance of the class
MyClassLongToCreateas we know that it is a slow operation, so we will get it lazily thanks to thegetmethod only when it is needed.Example for #3:
Here is a circular dependency that cannot be solved easily by the container such that some containers could just throw an exception as they don't know how to solve it by their own.
To fix it we use a
Provideron at least one of the constructors to break the circular dependency as next:This will allow the container to fully create an instance of
C1first (as we don't actually need to create an instance ofC2to inject a provider ofC2) once done the container will be able to create an instance ofC2from this instance ofC1.Example for #4:
Here you have a class
C2that is scoped to the session which depends onC1that itslef scoped to the request, we use a provider to allow us to get the instance ofC1corresponding to the current request as it will change from one request to another.