-
Notifications
You must be signed in to change notification settings - Fork 2
Guice
Pedro Felix edited this page Feb 9, 2011
·
11 revisions
- Instances provided by injectors
public interface Injector{
<T> T getInstance(Class<T> type)
...
}
- Injectors created by the
Guice
static class
public final class Guice{
static Injector createInjector(Module...)
}
-
Injector
creation is configured by modules -
A
Module
instance- is a binding collection
- defined using a fluent interface
bind(Service.class).to(ServiceImpl.class);
bind(Integer.class).annotatedWith(Names.named(“timeout”))
.toInstance(10);
- A
Binding
- maps types to their implementations
- is polymorphic: linked bindings, instance bindings
-
Linked bindings
- Allows for chaining
-
Instance bindings
-
Binding annotations
-
Provider bindings
-
@Provides
annotated method bindings -
Built-in bindings
- Loggers
- The injector
-
Just-In-Time bindings
-
Scopes define the instance lifetime
- Per injection
- Per application (singleton)
- Per session
- Per request
-
Constructor injection
- Public no-arguments constructor
- Constructor annotated with
@Inject
-
Method/setter injection
- Annotated with
@Inject
- Allows for
@Inject(optional=true)
- Annotated with
-
Field injection
-
On demand field injection
anInjector.injectMembers(aPreviouslyCreatedInstance);
- Providing injection
- Used for lazy or multiple instantiation
interface Provider<T>{
T get();
}
ctor(Service1 svc, ...){
// use svc instance
}
ctor(Provider<Service1> prov, ...){
// use prov to create as many instances as necessary,
// when necessary
}