Class Injector
Dependencies may be retrieved explicitly by calling getInstance(java.lang.Class<T>)
; transitive
dependencies will be automatically injected as needed. For a given injector, all calls to getInstance(java.lang.Class<T>)
are idempotent.
Dependencies are identified by an interface or class, and optionally by a name specified with
@Named
.
Dependency Resolution
When a dependency is requested, an implementation is sought.The injector looks for any instance that has been previously found for the given interface, or
that has been explicitly registered with Injector.Builder.bind(Class, Object)
or Injector.Builder.bind(Key, Object)
. If none is found, the injector searches for an implementing class
from the following sources, in order:
- Explicitly-registered implementations registered with
Injector.Builder.bind(Class, Class)
. - If the dependency type is an array or
Collection
, then its component type is recursively sought usingPluginFinder.findPlugins(Class)
and an array or collection of those instances is returned. - Plugin implementations published as
ServiceLoader
services under the dependency type (see alsoPluginFinder.findPlugin(Class)
). - Fallback default implementation classes registered with
Injector.Builder.bindDefault(Class, Class)
. - If the dependency type is a concrete class, then the dependency type itself.
AutoFactory
; see Scopes below).
If no implementing class is found in the injector or any superinjector, an exception is thrown.
Injection
When the injector has determined an implementing class, it attempts to instantiate it. It searches for a constructor in the following order:- A singular public constructor annotated @
Inject
. (If multiple constructors are @Inject
annotated, the injector will throw an exception.) - A singular public constructor of any arity.
- If no constructor has yet been found, the injector will throw an exception.
Scopes
If the dependency type is an interface annotated @AutoFactory
, then a factory object
implementing that interface is created; a new scoped injector is created for every method call to
the factory, with parameter arguments registered on the scoped injector.
Thread Safety
All methods are MT-safe.-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
Builder forInjector
.static class
Identifies an injection point. -
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescription<T> T
getInstance
(Class<T> type) Finds an instance for the given class.newScopeBuilder
(ClassLoader classLoader)
-
Constructor Details
-
Injector
public Injector()Creates a new empty injector.
-
-
Method Details
-
getInstance
Finds an instance for the given class. Calls are guaranteed idempotent. -
newScopeBuilder
-