Eager singletons

Guice provides special syntax for making an object that has the singleton scope, and is initialized to eager mode rather than lazy mode. Following is the syntax:

bind(NotificationService.class).to(SMSService.class).asEagerSingleton();

Eager singletons uncover initialization issues sooner, and guarantee end users get a reliable, smart encounter. Lazy singletons empower a quicker edit-compile-run development cycle. We can utilize the stage enum to indicate which procedure ought to be utilized.

The following table defines stage-wise use of syntax of the singleton and supported object initialize mode:

Syntax PRODUCTION DEVELOPMENT
@Singleton eager* lazy
.asEagerSingleton() eager eager
.in(Singleton.class) eager lazy ...

Get Java 9 Dependency Injection 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.