Another great feature of the CDI is to be able to control a lazy instantiation or resolution of a bean. This is done with the Provider<?> and Instance<?> APIs. Instance is a Provider allowing you to resolve a bean at runtime. Provider is an instance wrapper allowing you to decide when to instantiate the underlying instance.
Take a look at the following code snippet:
@ApplicationScopedpublic class DynamicInstance { @Inject private Provider<MyService> myServiceProvider; @Inject private Instance<MyService> myServices; public MyService currentService() { return myServiceProvider.get(); <1> } public MyService newService(final Annotation qualifier) { return myServices.select(qualifier).get(); <2> }}
Let's look at the underlying ...