Java EE 6:@Inject 和 Instance
我有一个关于 java ee 6 中的 @Inject
注释的问题:
之间有什么区别:
@Inject
private TestBean test;
@Inject
private Instance<TestBean> test2;
要获得参考:
test2.get();
有关实例的一些信息: http://docs.oracle.com/javaee/6/api/javax/enterprise/inject/Instance.html
也许它在 get() 调用之前不会创建对象?我只是想知道哪一个对jvm内存更好。我认为直接 @Inject
将直接创建对象的实例,即使应用程序没有使用它......
谢谢!
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 !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第二个是所谓的延迟注入或初始化。在大多数情况下,您的容器将选择执行定位、初始化和注入 TestBean 正确对象的工作,直到您调用 get() 为止。
至于“哪个更好”,你应该遵循优化规则。在出现问题之前不要进行优化,并使用分析器。
换句话说,除非您能明确证明第二个可以节省大量内存和 CPU,否则请使用第一个。
如果这回答了您的问题,请告诉我!
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!
有关 Instance 用例的更多信息可以在文档中找到:
在某些情况下,注入并不是获取上下文引用的最方便的方法。 情况下可能不会使用它:
例如,在以下 非常酷,所以您可以执行类似的操作
,因此您可以从 allMyCandidates 获取迭代器并迭代所有合格的对象。
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
So you can obtain an Iterator from allMyCandidates and iterate over all the qualified objects.