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 mostly does nothing; it "binds the ServiceImpl class to itself". You may
still want to use this if you prefer your Module class to serve as an explicit
manifest for the services it provides. In rare cases, Guice may be unable to validate a
binding at injector creation time unless it is given explicitly. When using hierarchical
injectors (via Binder.newPrivateBinder, Binder.PrivateModule, or Injector.createChildInjector), this guidance changes: see the note on hierarchical injectors in
Injector.createChildInjector .
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.
Constructor<T> loneCtor = getLoneCtorFromServiceImplViaReflection();
bind(ServiceImpl.class)
.toConstructor(loneCtor);
In 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 a
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, bindInterceptor, install, requestStaticInjection, addError 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 |
|---|---|
| public void | |
| public void | |
| public void | |
| public <T> LinkedBindingBuilder | |
| public <T> AnnotatedBindingBuilder | |
| public <T> AnnotatedBindingBuilder | |
| public AnnotatedConstantBindingBuilder | |
| public void | bindInterceptor(Matcher<? super Class<?>>
matches classes the interceptor should apply to. For example: classMatcher, Matcher<? super Method> only(Runnable.class).matches methods the interceptor should apply to. For example: methodMatcher, MethodInterceptor... annotatedWith(Transactional.class).to bind. The interceptors are called in the order they are given. interceptors)Binds method interceptor[s] to methods matched by class and method matchers. |
| public void | bindListener(Matcher<? super TypeLiteral<?>>
that matches injectable types the listener should be notified of typeMatcher, TypeListener for injectable types matched by typeMatcher listener)Registers a listener for injectable types. |
| public void | bindListener(Matcher<? super Binding<?>>
that matches bindings of provisioned objects the listener should be
notified of bindingMatcher, ProvisionListener... for provisioned objects matched by bindingMatcher listeners)Registers listeners for provisioned objects. |
| public void | |
| public void | convertToTypes(Matcher<? super TypeLiteral<?>>
matches types the converter can handle typeMatcher, TypeConverter converts values converter)Binds a type converter. |
| public Stage | |
| public void | disableCircularProxies()
Prevents Guice from injecting dependencies that form a cycle, unless broken by a |
| public <T> MembersInjector | getMembersInjector(TypeLiteral<T>
type to get members injector for typeLiteral)Returns the members injector used to inject dependencies into methods and fields on instances
of the given type |
| public <T> MembersInjector | getMembersInjector(Class<T>
type to get members injector for type)Returns the members injector used to inject dependencies into methods and fields on instances
of the given type |
| public <T> Provider | |
| public <T> Provider | getProvider(Dependency<T> dependency)
Returns the provider used to obtain instances for the given injection key. |
| public <T> Provider | getProvider(Class<T> type)
Returns the provider used to obtain instances for the given injection type. |
| public void | |
| public PrivateBinder | Returns: a binder that inherits configuration from this binder. Only exposed configuration on the returned binder will be visible to this binder.Creates a new private child environment for bindings and other configuration. |
| public <T> void | requestInjection(TypeLiteral<T>
of instance type, T for which members will be injected instance)Upon successful creation, the |
| public void | requestInjection(Object
for which members will be injected instance)Upon successful creation, the |
| public void | requestStaticInjection(Class<?>...
for which static members will be injected types)Upon successful creation, the |
| public void | requireAtInjectOnConstructors()
Requires that a @ |
| public void | |
| public void | requireExplicitBindings()
Instructs the Injector that bindings must be listed in a Module in order to be injected. |
| public 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. |
| public Binder | Returns: a binder that shares its configuration with this binder.library classes that create bindings on behalf of their clients. classesToSkip)Returns a binder that skips |
| public Binder | Returns: a binder that shares its configuration with this binderany object representing the source location and has a concise source)toString() valueReturns a binder that uses |
| addError | back to summary |
|---|---|
| public void addError(String message, Object... arguments) Records an error message which will be presented to the user at a later time. Unlike throwing
an exception, this enable us to continue configuring the Injector and discover more errors.
Uses | |
| addError | back to summary |
|---|---|
| public 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. If your Module calls something that you worry may fail, you should catch the exception and pass it into this. | |
| addError | back to summary |
|---|---|
| public void addError(Message message) Records an error message to be presented to the user at a later time.
| |
| bind | back to summary |
|---|---|
| public <T> LinkedBindingBuilder See the EDSL examples at | |
| bind | back to summary |
|---|---|
| public <T> AnnotatedBindingBuilder See the EDSL examples at | |
| bind | back to summary |
|---|---|
| public <T> AnnotatedBindingBuilder See the EDSL examples at | |
| bindConstant | back to summary |
|---|---|
| public AnnotatedConstantBindingBuilder bindConstant() See the EDSL examples at | |
| bindInterceptor | back to summary |
|---|---|
| public void bindInterceptor(Matcher<? super Class<?>> classMatcher, Matcher<? super Method> methodMatcher, MethodInterceptor... interceptors) Binds method interceptor[s] to methods matched by class and method matchers. A method is eligible for interception if:
Note this API only works if
| |
| bindListener | back to summary |
|---|---|
| public void bindListener(Matcher<? super TypeLiteral<?>> typeMatcher, TypeListener listener) Registers a listener for injectable types. Guice will notify the listener when it encounters injectable types matched by the given type matcher.
| |
| bindListener | back to summary |
|---|---|
| public void bindListener(Matcher<? super Binding<?>> bindingMatcher, ProvisionListener... listeners) Registers listeners for provisioned objects. Guice will notify the listeners just before and
after the object is provisioned. Provisioned objects that are also injectable (everything
except objects provided through Providers) can also be notified through TypeListeners
registered in
| |
| bindScope | back to summary |
|---|---|
| public void bindScope(Class<? extends Annotation> annotationType, Scope scope) Binds a scope to an annotation. | |
| convertToTypes | back to summary |
|---|---|
| public void convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter converter) Binds a type converter. The injector will use the given converter to convert string constants to matching types as needed.
| |
| currentStage | back to summary |
|---|---|
| public Stage currentStage() Gets the current stage. | |
| disableCircularProxies | back to summary |
|---|---|
| public void disableCircularProxies() Prevents Guice from injecting dependencies that form a cycle, unless broken by a 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.
| |
| getMembersInjector | back to summary |
|---|---|
| public <T> MembersInjector Returns the members injector used to inject dependencies into methods and fields on instances
of the given type
| |
| getMembersInjector | back to summary |
|---|---|
| public <T> MembersInjector Returns the members injector used to inject dependencies into methods and fields on instances
of the given type
| |
| getProvider | back to summary |
|---|---|
| public <T> Provider Returns the provider used to obtain instances for the given injection key. The returned
provider will not be valid until the
| |
| getProvider | back to summary |
|---|---|
| public <T> Provider Returns the provider used to obtain instances for the given injection key. The returned
provider will be attached to the injection point and will follow the nullability specified in
the dependency. Additionally, the returned provider will not be valid until the
| |
| getProvider | back to summary |
|---|---|
| public <T> Provider Returns the provider used to obtain instances for the given injection type. The returned
provider will not be valid until the
| |
| install | back to summary |
|---|---|
| public void install(Module module) Uses the given module to configure more bindings. | |
| newPrivateBinder | back to summary |
|---|---|
| public PrivateBinder newPrivateBinder() Creates a new private child environment for bindings and other configuration. The returned
binder can be used to add and configuration information in this environment. See
| |
| requestInjection | back to summary |
|---|---|
| public <T> void requestInjection(TypeLiteral<T> type, T instance) Upon successful creation, the
| |
| requestInjection | back to summary |
|---|---|
| public void requestInjection(Object instance) Upon successful creation, the
| |
| requestStaticInjection | back to summary |
|---|---|
| public void requestStaticInjection(Class<?>... types) Upon successful creation, the
| |
| requireAtInjectOnConstructors | back to summary |
|---|---|
| public void requireAtInjectOnConstructors() Requires that a @ If the class is bound using
| |
| requireExactBindingAnnotations | back to summary |
|---|---|
| public void requireExactBindingAnnotations() Requires that Guice finds an exactly matching binding annotation. This disables the error-prone
feature in Guice where it can substitute a binding for
| |
| requireExplicitBindings | back to summary |
|---|---|
| public void requireExplicitBindings() Instructs the Injector that bindings must be listed in a Module in order to be injected.
Classes that are not explicitly bound in a module cannot be injected. Bindings created through
a linked binding ( Tools can still retrieve bindings for implicit bindings (bindings created through a linked
binding) if explicit bindings are required, however 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.
| |
| scanModulesForAnnotatedMethods | back to summary |
|---|---|
| public 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. Scanners apply to all modules installed in the injector. Scanners installed in child injectors or private modules do not impact modules in siblings or parents, however scanners installed in parents do apply to all child injectors and private modules.
| |
| skipSources | back to summary |
|---|---|
| public Binder skipSources(Class<?>... classesToSkip) Returns a binder that skips | |
| withSource | back to summary |
|---|---|
| public Binder withSource(Object source) Returns a binder that uses
| |