I have a question about the @Inject
annotation in java ee 6 :
What is the difference between :
@Inject
private TestBean test;
@Inject
private Instance<TestBean> test2;
To have the reference :
test2.get();
Some infos about Instance : http://docs.oracle.com/javaee/6/api/javax/enterprise/inject/Instance.html
Maybe it's doesnt create the object until it's called by get() ? I just wanted to know which one is better for the jvm memory. I think direct @Inject
will directly create an instance of the object , even if it's not used by the appplication...
Thank you !
The second is what's called deferred injection or initialization. Your container will elect do do the work of locating, initializing, and injecting the proper object for TestBean until you call get() in most circumstances.
As far as "which one is better", you should defer to the rules of optimization. Don't optimize until you have a problem, and use a profiler.
Another words, use the first one unless you can definitively prove the second one is saving you significant amounts of memory and cpu.
Let me know if that answers your question!
Further information on use cases for Instance can be found in documentation:
In certain situations, injection is not the most convenient way to obtain a contextual reference. For example, it may not be used when:
This is pretty cool so you can do something like
@Inject @MyQualifier Instance<MyType> allMycandidates;
So you can obtain an Iterator from allMyCandidates and iterate over all the qualified objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With