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:

public class Index {

    Provider<Boundary> boundary;

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


The injected component is unaware about the laziness:

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!


Will it scan classpath dynamically like instance does ? or will it stick to first found implementation ? :)

Posted by psychollek on October 21, 2014 at 10:14 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments