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;
Provider<T>
is a JSR-330 interface which is extended by the CDI interfaceInstance<T>
.Injecting
MyBean
, your application will throw an exception during startup when there is no matching bean or more than one matching bean.Injecting
Instance<MyBean>
, bean resolution is delegated to the application: you can iterate over all candidate beans andselect()
the one you want or callisUnsatisfied()
and decide what to do when there is no matching bean.For beans with
@Dependent
scope, callingInstance.get()
will create a new instance for each invocation, and you should invokeInstance.destroy(t)
for each such instance when you no longer need it.Provider
just has theget()
method, but nodestroy()
orselect()
and does not support iteration. In a CDI environment, for any use case addressed byProvider<T>
, you had better useInstance<T>
instead.