何时应该实例< T>和提供者< T>用于在CDI注入豆类? [英] When should Instance<T> and Provider<T> be used to inject beans in CDI?

查看:124
本文介绍了何时应该实例< T>和提供者< T>用于在CDI注入豆类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读的API文档实例< T> 提供商< T> ,但是应该何时使用它们并不完全清楚。

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.

这篇关于何时应该实例&lt; T&gt;和提供者&lt; T&gt;用于在CDI注入豆类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆