-
Notifications
You must be signed in to change notification settings - Fork 180
Lazy Singleton
Randgalt edited this page Sep 14, 2012
·
3 revisions
Guice can inject instances as a singletons. Depending on the mode that Guice is in, it will lazily create the singletons (i.e. only when they are needed) or eagerly create them (i.e. when the Injector is created).
By default, Governator sets the Guice mode to Stage.PRODUCTION
which causes singletons to be eager. Guice does not provide a lazy singleton scope. This is added by Governator.
You can use lazy singleton either by annotating a class with @LazySingleton
or using the LazySingletonScope when binding. E.g.
binder.bind(IFace.class).to(Impl.class).in(LazySingletonScope.get())
LazySingleton comes in handy when you need to have fine grained control over when an instance is created. You can do this by using a provider in conjunction with LazySingleton. E.g.
// an example class
@LazySingleton
public class MyClass
...
// inject a provider instead of the instance
public class Foo
{
private final Provider<MyClass> myClassProvider;
@Inject
public foo(Provider<MyClass> myClassProvider)
{
this.myClassProvider = myClassProvider;
}
...
// somewhere else in the class
myClassProvider.get(); // object will be created here
}
- Home
- Getting Started
- Bootstrapping
- Lifecycle Management
- Auto Binding
- Module-Dependencies
- Warm Up
- Configuration Mapping
- Field Validation
- Lazy Singleton
- Concurrent Singleton
- Generic Binding Annotations
- LifecycleListener
- Governator Phases
- Grapher Integration
- JUnit Testing
- FAQ
- Best Practices
- Spring, PicoContainer, Etc.
- Javadoc
- End-to-End Examples