问题描述
我一直在阅读和,但是应该何时使用它们并不完全清楚。
I've been reading the API documentation of Instance<T>
and Provider<T>
, but it isn't completely clear when they should be used.
以下方法之间的区别是什么?
What's the difference between the following approaches?
@Inject
MyBean bean;
@Inject
Instance<MyBean> bean;
@Inject
Provider<MyBean> bean;
推荐答案
提供商< T>
是一个JSR-330接口,由CDI接口扩展 Instance< T>
。
Provider<T>
is a JSR-330 interface which is extended by the CDI interface Instance<T>
.
注入 MyBean
,当没有匹配的bean或多个匹配的bean时,你的应用程序将在启动期间抛出异常。
Injecting MyBean
, your application will throw an exception during startup when there is no matching bean or more than one matching bean.
注入实例< MyBean>
,将bean解析委托给应用程序:您可以遍历所有候选bean并且 select()
你想要的那个或者叫 isUnsatisfied()
并决定当没有匹配的bean时该怎么办。
Injecting Instance<MyBean>
, bean resolution is delegated to the application: you can iterate over all candidate beans and select()
the one you want or call isUnsatisfied()
and decide what to do when there is no matching bean.
对于 @Dependent
范围的bean,调用 Instance.get()
将为每个bean创建一个新实例调用,当你不再需要它时,你应该为每个这样的实例调用 Instance.destroy(t)
。
For beans with @Dependent
scope, calling Instance.get()
will create a new instance for each invocation, and you should invoke Instance.destroy(t)
for each such instance when you no longer need it.
提供商
只有 get()
方法,但没有 des troy()
或 select()
并且不支持迭代。在CDI环境中,对于 Provider< T>
解决的任何用例,最好使用 Instance< T>
代替。
Provider
just has the get()
method, but no destroy()
or select()
and does not support iteration. In a CDI environment, for any use case addressed by Provider<T>
, you had better use Instance<T>
instead.
这篇关于何时应该实例< T>和提供者< T>用于在CDI注入豆类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!