public interface Binder
Injector
. Guice provides this object to your application's Module
implementors so
they may each contribute their own bindings and other registrations.
binder
, just as you will if your module extends AbstractModule
.
bind(ServiceImpl.class);This statement does essentially nothing; it "binds the
ServiceImpl
class to itself" and
does not change Guice's default behavior. You may still want to use this if you prefer your
Module
class to serve as an explicit manifest for the services it provides. Also,
in rare cases, Guice may be unable to validate a binding at injector creation time unless it is
given explicitly.
bind(Service.class).to(ServiceImpl.class);Specifies that a request for a
Service
instance with no binding annotations should be
treated as if it were a request for a ServiceImpl
instance. This overrides the
function of any @ImplementedBy
or @ProvidedBy
annotations found on Service
, since Guice will have already "moved on" to ServiceImpl
before it reaches the point when it starts looking for these annotations.
bind(Service.class).toProvider(ServiceProvider.class);In this example,
ServiceProvider
must extend or implement Provider<Service>
. This
binding specifies that Guice should resolve an unannotated injection request for Service
by first resolving an instance of ServiceProvider
in the regular way, then calling get()
on the resulting Provider instance to obtain the Service
instance.
The Provider
you use here does not have to be a "factory"; that is, a provider which
always creates each instance it provides. However, this is generally a good practice to
follow. You can then use Guice's concept of scopes
to guide when creation should
happen -- "letting Guice work for you".
bind(Service.class).annotatedWith(Red.class).to(ServiceImpl.class);Like the previous example, but only applies to injection requests that use the binding annotation
@Red
. If your module also includes bindings for particular values of the
@Red
annotation (see below), then this binding will serve as a "catch-all" for any values
of @Red
that have no exact match in the bindings.
bind(ServiceImpl.class).in(Singleton.class); // or, alternatively bind(ServiceImpl.class).in(Scopes.SINGLETON);Either of these statements places the
ServiceImpl
class into singleton scope. Guice will
create only one instance of ServiceImpl
and will reuse it for all injection requests of
this type. Note that it is still possible to bind another instance of ServiceImpl
if the
second binding is qualified by an annotation as in the previous example. Guice is not overly
concerned with preventing you from creating multiple instances of your "singletons", only
with enabling your application to share only one instance if that's all you tell Guice you
need.
Note: a scope specified in this way overrides any scope that was specified with
an annotation on the ServiceImpl
class.
Besides Singleton
/Scopes.SINGLETON
, there are servlet-specific scopes
available in com.google.inject.servlet.ServletScopes
, and your Modules can contribute
their own custom scopes for use here as well.
bind(new TypeLiteral<PaymentService<CreditCard>>() {}) .to(CreditCardPaymentService.class);This admittedly odd construct is the way to bind a parameterized type. It tells Guice how to honor an injection request for an element of type
PaymentService<CreditCard>
. The class
CreditCardPaymentService
must implement the PaymentService<CreditCard>
interface.
Guice cannot currently bind or inject a generic type, such as Set<E>
; all type parameters
must be fully specified.
bind(Service.class).toInstance(new ServiceImpl()); // or, alternatively bind(Service.class).toInstance(SomeLegacyRegistry.getService());In this example, your module itself, not Guice, takes responsibility for obtaining a
ServiceImpl
instance, then asks Guice to always use this single instance to fulfill all
Service
injection requests. When the Injector
is created, it will automatically
perform field and method injection for this instance, but any injectable constructor on ServiceImpl
is simply ignored. Note that using this approach results in "eager loading" behavior
that you can't control.
bindConstant().annotatedWith(ServerHost.class).to(args[0]);Sets up a constant binding. Constant injections must always be annotated. When a constant binding's value is a string, it is eligible for conversion to all primitive types, to
all enums
, and to class literals
. Conversions
for other types can be configured using convertToTypes()
.
@Color("red") Color red; // A member variable (field) . . . red = MyModule.class.getDeclaredField("red").getAnnotation(Color.class); bind(Service.class).annotatedWith(red).to(RedService.class);If your binding annotation has parameters you can apply different bindings to different specific values of your annotation. Getting your hands on the right instance of the annotation is a bit of a pain -- one approach, shown above, is to apply a prototype annotation to a field in your module class, so that you can read this annotation instance and give it to Guice.
bind(Service.class) .annotatedWith(Names.named("blue")) .to(BlueService.class);Differentiating by names is a common enough use case that we provided a standard annotation,
@Named
. Because of Guice's library support, binding by name
is quite easier than in the arbitrary binding annotation case we just saw. However, remember that
these names will live in a single flat namespace with all the other names used in your
application.
ConstructorIn this example, we directly tell Guice which constructor to use in a concrete class implementation. It means that we do not need to place @Inject on any of the constructors and that Guice treats the provided constructor as though it were annotated so. It is useful for cases where you cannot modify existing classes and is a bit simpler than using aloneCtor = getLoneCtorFromServiceImplViaReflection(); bind(ServiceImpl.class) .toConstructor(loneCtor);
Provider
.
The above list of examples is far from exhaustive. If you can think of how the concepts of one example might coexist with the concepts from another, you can most likely weave the two together. If the two concepts make no sense with each other, you most likely won't be able to do it. In a few cases Guice will let something bogus slip by, and will then inform you of the problems at runtime, as soon as you try to create your Injector.
The other methods of Binder such as bindScope(java.lang.Class<? extends java.lang.annotation.Annotation>, com.google.inject.Scope)
, bindInterceptor(com.google.inject.matcher.Matcher<? super java.lang.Class<?>>, com.google.inject.matcher.Matcher<? super java.lang.reflect.Method>, org.aopalliance.intercept.MethodInterceptor...)
, install(com.google.inject.Module)
, requestStaticInjection(java.lang.Class<?>...)
, addError(java.lang.String, java.lang.Object...)
and currentStage()
are not
part of the Binding EDSL; you can learn how to use these in the usual way, from the method
documentation.
Modifier and Type | Method and Description |
---|---|
void |
addError(Message message)
Records an error message to be presented to the user at a later time.
|
void |
addError(String message,
Object... arguments)
Records an error message which will be presented to the user at a later time.
|
void |
addError(Throwable t)
Records an exception, the full details of which will be logged, and the message of which will
be presented to the user at a later time.
|
<T> AnnotatedBindingBuilder<T> |
bind(Class<T> type)
See the EDSL examples at
Binder . |
<T> LinkedBindingBuilder<T> |
bind(Key<T> key)
See the EDSL examples at
Binder . |
<T> AnnotatedBindingBuilder<T> |
bind(TypeLiteral<T> typeLiteral)
See the EDSL examples at
Binder . |
AnnotatedConstantBindingBuilder |
bindConstant()
See the EDSL examples at
Binder . |
void |
bindInterceptor(Matcher<? super Class<?>> classMatcher,
Matcher<? super Method> methodMatcher,
org.aopalliance.intercept.MethodInterceptor... interceptors)
Binds method interceptor[s] to methods matched by class and method matchers.
|
void |
bindListener(Matcher<? super Binding<?>> bindingMatcher,
ProvisionListener... listeners)
Registers listeners for provisioned objects.
|
void |
bindListener(Matcher<? super TypeLiteral<?>> typeMatcher,
TypeListener listener)
Registers a listener for injectable types.
|
void |
bindScope(Class<? extends Annotation> annotationType,
Scope scope)
Binds a scope to an annotation.
|
void |
convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher,
TypeConverter converter)
Binds a type converter.
|
Stage |
currentStage()
Gets the current stage.
|
void |
disableCircularProxies()
Prevents Guice from injecting dependencies that form a cycle, unless broken by a
Provider . |
<T> MembersInjector<T> |
getMembersInjector(Class<T> type)
Returns the members injector used to inject dependencies into methods and fields on instances
of the given type
T . |
<T> MembersInjector<T> |
getMembersInjector(TypeLiteral<T> typeLiteral)
Returns the members injector used to inject dependencies into methods and fields on instances
of the given type
T . |
<T> Provider<T> |
getProvider(Class<T> type)
Returns the provider used to obtain instances for the given injection type.
|
<T> Provider<T> |
getProvider(Dependency<T> dependency)
Returns the provider used to obtain instances for the given injection key.
|
<T> Provider<T> |
getProvider(Key<T> key)
Returns the provider used to obtain instances for the given injection key.
|
void |
install(Module module)
Uses the given module to configure more bindings.
|
PrivateBinder |
newPrivateBinder()
Creates a new private child environment for bindings and other configuration.
|
void |
requestInjection(Object instance)
Upon successful creation, the
Injector will inject instance fields and methods of the
given object. |
<T> void |
requestInjection(TypeLiteral<T> type,
T instance)
Upon successful creation, the
Injector will inject instance fields and methods of the
given object. |
void |
requestStaticInjection(Class<?>... types)
Upon successful creation, the
Injector will inject static fields and methods in the
given classes. |
void |
requireAtInjectOnConstructors()
Requires that a @
Inject annotation exists on a constructor in order for
Guice to consider it an eligible injectable class. |
void |
requireExactBindingAnnotations()
Requires that Guice finds an exactly matching binding annotation.
|
void |
requireExplicitBindings()
Instructs the Injector that bindings must be listed in a Module in order to be injected.
|
void |
scanModulesForAnnotatedMethods(ModuleAnnotatedMethodScanner scanner)
Adds a scanner that will look in all installed modules for annotations the scanner can parse,
and binds them like @Provides methods.
|
Binder |
skipSources(Class... classesToSkip)
Returns a binder that skips
classesToSkip when identify the calling code. |
Binder |
withSource(Object source)
Returns a binder that uses
source as the reference location for configuration errors. |
void bindInterceptor(Matcher<? super Class<?>> classMatcher, Matcher<? super Method> methodMatcher, org.aopalliance.intercept.MethodInterceptor... interceptors)
classMatcher
- matches classes the interceptor should apply to. For example: only(Runnable.class)
.methodMatcher
- matches methods the interceptor should apply to. For example: annotatedWith(Transactional.class)
.interceptors
- to bind. The interceptors are called in the order they are given.void bindScope(Class<? extends Annotation> annotationType, Scope scope)
<T> LinkedBindingBuilder<T> bind(Key<T> key)
Binder
.<T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral)
Binder
.<T> AnnotatedBindingBuilder<T> bind(Class<T> type)
Binder
.AnnotatedConstantBindingBuilder bindConstant()
Binder
.<T> void requestInjection(TypeLiteral<T> type, T instance)
Injector
will inject instance fields and methods of the
given object.type
- of instanceinstance
- for which members will be injectedvoid requestInjection(Object instance)
Injector
will inject instance fields and methods of the
given object.instance
- for which members will be injectedvoid requestStaticInjection(Class<?>... types)
Injector
will inject static fields and methods in the
given classes.types
- for which static members will be injectedvoid install(Module module)
Stage currentStage()
void addError(String message, Object... arguments)
String.format(String, Object[])
to insert the arguments into the message.void addError(Throwable t)
void addError(Message message)
<T> Provider<T> getProvider(Key<T> key)
Injector
has been created. The provider will throw
an IllegalStateException
if you try to use it beforehand.<T> Provider<T> getProvider(Dependency<T> dependency)
Injector
has been created. The provider will throw an IllegalStateException
if you try
to use it beforehand.<T> Provider<T> getProvider(Class<T> type)
Injector
has been created. The provider will throw
an IllegalStateException
if you try to use it beforehand.<T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral)
T
. The returned members injector will not be valid until the main
Injector
has been created. The members injector will throw an IllegalStateException
if you try to use it beforehand.typeLiteral
- type to get members injector for<T> MembersInjector<T> getMembersInjector(Class<T> type)
T
. The returned members injector will not be valid until the main
Injector
has been created. The members injector will throw an IllegalStateException
if you try to use it beforehand.type
- type to get members injector forvoid convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter converter)
typeMatcher
- matches types the converter can handleconverter
- converts valuesvoid bindListener(Matcher<? super TypeLiteral<?>> typeMatcher, TypeListener listener)
typeMatcher
- that matches injectable types the listener should be notified oflistener
- for injectable types matched by typeMatchervoid bindListener(Matcher<? super Binding<?>> bindingMatcher, ProvisionListener... listeners)
bindListener(com.google.inject.matcher.Matcher<? super com.google.inject.TypeLiteral<?>>, com.google.inject.spi.TypeListener)
.bindingMatcher
- that matches bindings of provisioned objects the listener should be
notified oflisteners
- for provisioned objects matched by bindingMatcherBinder withSource(Object source)
source
as the reference location for configuration errors.
This is typically a StackTraceElement
for .java
source but it could any binding
source, such as the path to a .properties
file.source
- any object representing the source location and has a concise toString()
valueBinder skipSources(Class... classesToSkip)
classesToSkip
when identify the calling code. The caller's
StackTraceElement
is used to locate the source of configuration errors.classesToSkip
- library classes that create bindings on behalf of their clients.PrivateBinder newPrivateBinder()
PrivateModule
for details.void requireExplicitBindings()
bind(Foo.class).to(FooImpl.class)
) are allowed, but the implicit
binding (FooImpl
) cannot be directly injected unless it is also explicitly bound (
bind(FooImpl.class)
).
Tools can still retrieve bindings for implicit bindings (bindings created through a linked
binding) if explicit bindings are required, however Binding.getProvider()
will fail.
By default, explicit bindings are not required.
If a parent injector requires explicit bindings, then all child injectors (and private modules within that injector) also require explicit bindings. If a parent does not require explicit bindings, a child injector or private module may optionally declare itself as requiring explicit bindings. If it does, the behavior is limited only to that child or any grandchildren. No siblings of the child will require explicit bindings.
In the absence of an explicit binding for the target, linked bindings in child injectors create a binding for the target in the parent. Since this behavior can be surprising, it causes an error instead if explicit bindings are required. To avoid this error, add an explicit binding for the target, either in the child or the parent.
void disableCircularProxies()
Provider
. By default, circular dependencies are not disabled.
If a parent injector disables circular dependencies, then all child injectors (and private modules within that injector) also disable circular dependencies. If a parent does not disable circular dependencies, a child injector or private module may optionally declare itself as disabling circular dependencies. If it does, the behavior is limited only to that child or any grandchildren. No siblings of the child will disable circular dependencies.
void requireAtInjectOnConstructors()
Inject
annotation exists on a constructor in order for
Guice to consider it an eligible injectable class. By default, Guice will inject classes that
have a no-args constructor if no @Inject
annotation exists on any
constructor.
If the class is bound using LinkedBindingBuilder.toConstructor(java.lang.reflect.Constructor<S>)
, Guice will still
inject that constructor regardless of annotations.
void requireExactBindingAnnotations()
@Named Foo
when
attempting to inject @Named("foo") Foo
.void scanModulesForAnnotatedMethods(ModuleAnnotatedMethodScanner scanner)
Copyright © 2006–2020 Google, Inc.. All rights reserved.