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!


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 7: Bootstrap, Effective, Architectures, Web, React and Angular, Testing and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

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
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License