adam bien's blog

Lazy Injection with javax.inject.Provider 📎

javax.inject.Provider is the minimalistic version of the javax.enterprise.inject.Instance interface. In fact Instance inherits from Provider

For on-demand injection of components / resources inject them as Provider:


@Model
public class Index {

    @Inject
    Provider<Boundary> boundary;

    public String getMessage() {
        return boundary.get().message();
    }

}

The injected component is unaware about the laziness:


@Stateless
public class Boundary {

    public String message() {
        return "Good morning";
    }
}

Instance comes with additional functionality: see also Interfaces on Demand with CDI and EJB 3.1

[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 235 in, chapter "Plugin"]

See you at Java EE Workshops at Munich Airport, particularly at: Effective Java EE 7!