public interface Injector extends AutoCloseable
Injector uses dependency injection to act as a factory for creating instances
with complex dependencies. A default implementation of Injector can easily be
created by using an InjectorBuilder
:
InjectorBuilder b = new InjectorBuilder(); b.bind(Foo.class).to(Bar.class); b.applyModule(new MyCustomModule()); // other bindings Injector i = b.build(); assert (i.getInstance(Foo.class) instanceof Bar);
Alternatively, BindingFunctionBuilder
and DependencySolver
can be used to create your own Injector implementations.
Modifier and Type | Method and Description |
---|---|
void |
close()
Close the injector, shutting down any instantiated components that require shutdown.
|
<T> T |
getInstance(Annotation qualifier,
Class<T> type)
Get an instance of T with the given
Qualifier annotation. |
<T> T |
getInstance(Class<T> type)
Get an instance of T based on the bindings that this Injector was
configured with.
|
<T> T |
tryGetInstance(Annotation qualifier,
Class<T> type)
Try to get an instance of a component, returning
null if the component
does not have a configured implementation. |
@Nonnull <T> T getInstance(Class<T> type) throws InjectionException
Injectors may memoize or cache previously created objects. As an example,
the Injector created by InjectorBuilder
reuses instances where
possible.
T
- The object type being createdtype
- The class typeConstructionException
- if type cannot be instantiatedInjectionException
@Nonnull <T> T getInstance(Annotation qualifier, Class<T> type) throws InjectionException
Qualifier
annotation.T
- The object typequalifier
- The qualifier on of the returned instancetype
- The class typeConstructionException
- if type cannot be instantiatedInjectionException
@Nullable <T> T tryGetInstance(Annotation qualifier, Class<T> type) throws InjectionException
null
if the component
does not have a configured implementation.T
- The component type.qualifier
- The qualifier, or null
for an unqualified component.type
- The component type.T
, or null
if no implemenation of T
is configured.InjectionException
- if there is some other error injecting the instance.void close()
close
in interface AutoCloseable
Copyright © 2016 GroupLens Research. All rights reserved.