Dynamic lookups

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 ...

Get Java EE 8 High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.