Interface Binder
-
- All Known Subinterfaces:
PrivateBinder
public interface BinderCollects configuration information (primarily bindings) which will be used to create anInjector. Guice provides this object to your application'sModuleimplementors so they may each contribute their own bindings and other registrations.The Guice Binding EDSL
Guice uses an embedded domain-specific language, or EDSL, to help you create bindings simply and readably. This approach is great for overall usability, but it does come with a small cost: it is difficult to learn how to use the Binding EDSL by reading method-level javadocs. Instead, you should consult the series of examples below. To save space, these examples omit the opening
binder, just as you will if your module extendsAbstractModule.bind(ServiceImpl.class);This statement does essentially nothing; it "binds theServiceImplclass to itself" and does not change Guice's default behavior. You may still want to use this if you prefer yourModuleclass 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 aServiceinstance with no binding annotations should be treated as if it were a request for aServiceImplinstance. This overrides the function of any@ImplementedByor@ProvidedByannotations found onService, since Guice will have already "moved on" toServiceImplbefore it reaches the point when it starts looking for these annotations.bind(Service.class).toProvider(ServiceProvider.class);In this example,ServiceProvidermust extend or implementProvider<Service>. This binding specifies that Guice should resolve an unannotated injection request forServiceby first resolving an instance ofServiceProviderin the regular way, then callingget()on the resulting Provider instance to obtain theServiceinstance.The
Provideryou 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 ofscopesto 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@Redannotation (see below), then this binding will serve as a "catch-all" for any values of@Redthat 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 theServiceImplclass into singleton scope. Guice will create only one instance ofServiceImpland will reuse it for all injection requests of this type. Note that it is still possible to bind another instance ofServiceImplif 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
ServiceImplclass.Besides
Singleton/Scopes.SINGLETON, there are servlet-specific scopes available incom.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 typePaymentService<CreditCard>. The classCreditCardPaymentServicemust implement thePaymentService<CreditCard>interface. Guice cannot currently bind or inject a generic type, such asSet<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 aServiceImplinstance, then asks Guice to always use this single instance to fulfill allServiceinjection requests. When theInjectoris created, it will automatically perform field and method injection for this instance, but any injectable constructor onServiceImplis 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, toall enums, and toclass literals. Conversions for other types can be configured usingconvertToTypes().@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.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>, org.elasticsearch.common.inject.Scope),install(org.elasticsearch.common.inject.Module),requestStaticInjection(java.lang.Class<?>...),addError(java.lang.String, java.lang.Object...)andcurrentStage()are not part of the Binding EDSL; you can learn how to use these in the usual way, from the method documentation.
-
-
Method Summary
Modifier and Type Method Description voidaddError(java.lang.String message, java.lang.Object... arguments)Records an error message which will be presented to the user at a later time.voidaddError(java.lang.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.voidaddError(Message message)Records an error message to be presented to the user at a later time.<T> AnnotatedBindingBuilder<T>bind(java.lang.Class<T> type)See the EDSL examples atBinder.<T> LinkedBindingBuilder<T>bind(Key<T> key)See the EDSL examples atBinder.<T> AnnotatedBindingBuilder<T>bind(TypeLiteral<T> typeLiteral)See the EDSL examples atBinder.AnnotatedConstantBindingBuilderbindConstant()See the EDSL examples atBinder.voidbindListener(Matcher<? super TypeLiteral<?>> typeMatcher, TypeListener listener)Registers a listener for injectable types.voidbindScope(java.lang.Class<? extends java.lang.annotation.Annotation> annotationType, Scope scope)Binds a scope to an annotation.voidconvertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter converter)Binds a type converter.StagecurrentStage()Gets the current stage.<T> MembersInjector<T>getMembersInjector(java.lang.Class<T> type)Returns the members injector used to inject dependencies into methods and fields on instances of the given typeT.<T> MembersInjector<T>getMembersInjector(TypeLiteral<T> typeLiteral)Returns the members injector used to inject dependencies into methods and fields on instances of the given typeT.<T> Provider<T>getProvider(java.lang.Class<T> type)Returns the provider used to obtain instances for the given injection type.<T> Provider<T>getProvider(Key<T> key)Returns the provider used to obtain instances for the given injection key.voidinstall(Module module)Uses the given module to configure more bindings.PrivateBindernewPrivateBinder()Creates a new private child environment for bindings and other configuration.voidrequestInjection(java.lang.Object instance)Upon successful creation, theInjectorwill inject instance fields and methods of the given object.<T> voidrequestInjection(TypeLiteral<T> type, T instance)Upon successful creation, theInjectorwill inject instance fields and methods of the given object.voidrequestStaticInjection(java.lang.Class<?>... types)Upon successful creation, theInjectorwill inject static fields and methods in the given classes.BinderskipSources(java.lang.Class<?>... classesToSkip)Returns a binder that skipsclassesToSkipwhen identify the calling code.BinderwithSource(java.lang.Object source)Returns a binder that usessourceas the reference location for configuration errors.
-
-
-
Method Detail
-
bindScope
void bindScope(java.lang.Class<? extends java.lang.annotation.Annotation> annotationType, Scope scope)Binds a scope to an annotation.
-
bind
<T> LinkedBindingBuilder<T> bind(Key<T> key)
See the EDSL examples atBinder.
-
bind
<T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral)
See the EDSL examples atBinder.
-
bind
<T> AnnotatedBindingBuilder<T> bind(java.lang.Class<T> type)
See the EDSL examples atBinder.
-
bindConstant
AnnotatedConstantBindingBuilder bindConstant()
See the EDSL examples atBinder.
-
requestInjection
<T> void requestInjection(TypeLiteral<T> type, T instance)
Upon successful creation, theInjectorwill inject instance fields and methods of the given object.- Parameters:
type- of instanceinstance- for which members will be injected- Since:
- 2.0
-
requestInjection
void requestInjection(java.lang.Object instance)
Upon successful creation, theInjectorwill inject instance fields and methods of the given object.- Parameters:
instance- for which members will be injected- Since:
- 2.0
-
requestStaticInjection
void requestStaticInjection(java.lang.Class<?>... types)
Upon successful creation, theInjectorwill inject static fields and methods in the given classes.- Parameters:
types- for which static members will be injected
-
install
void install(Module module)
Uses the given module to configure more bindings.
-
currentStage
Stage currentStage()
Gets the current stage.
-
addError
void addError(java.lang.String message, java.lang.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. UsesString.format(String, Object[])to insert the arguments into the message.
-
addError
void addError(java.lang.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
void addError(Message message)
Records an error message to be presented to the user at a later time.- Since:
- 2.0
-
getProvider
<T> Provider<T> getProvider(Key<T> key)
Returns the provider used to obtain instances for the given injection key. The returned will not be valid until theInjectorhas been created. The provider will throw anIllegalStateExceptionif you try to use it beforehand.- Since:
- 2.0
-
getProvider
<T> Provider<T> getProvider(java.lang.Class<T> type)
Returns the provider used to obtain instances for the given injection type. The returned provider will not be valid until theInjectorhas been created. The provider will throw anIllegalStateExceptionif you try to use it beforehand.- Since:
- 2.0
-
getMembersInjector
<T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral)
Returns the members injector used to inject dependencies into methods and fields on instances of the given typeT. The returned members injector will not be valid until the mainInjectorhas been created. The members injector will throw anIllegalStateExceptionif you try to use it beforehand.- Parameters:
typeLiteral- type to get members injector for- Since:
- 2.0
-
getMembersInjector
<T> MembersInjector<T> getMembersInjector(java.lang.Class<T> type)
Returns the members injector used to inject dependencies into methods and fields on instances of the given typeT. The returned members injector will not be valid until the mainInjectorhas been created. The members injector will throw anIllegalStateExceptionif you try to use it beforehand.- Parameters:
type- type to get members injector for- Since:
- 2.0
-
convertToTypes
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.- Parameters:
typeMatcher- matches types the converter can handleconverter- converts values- Since:
- 2.0
-
bindListener
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.- Parameters:
typeMatcher- that matches injectable types the listener should be notified oflistener- for injectable types matched by typeMatcher- Since:
- 2.0
-
withSource
Binder withSource(java.lang.Object source)
Returns a binder that usessourceas the reference location for configuration errors. This is typically aStackTraceElementfor.javasource but it could any binding source, such as the path to a.propertiesfile.- Parameters:
source- any object representing the source location and has a concisetoString()value- Returns:
- a binder that shares its configuration with this binder
- Since:
- 2.0
-
skipSources
Binder skipSources(java.lang.Class<?>... classesToSkip)
Returns a binder that skipsclassesToSkipwhen identify the calling code. The caller'sStackTraceElementis used to locate the source of configuration errors.- Parameters:
classesToSkip- library classes that create bindings on behalf of their clients.- Returns:
- a binder that shares its configuration with this binder.
- Since:
- 2.0
-
newPrivateBinder
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. SeePrivateModulefor details.- Returns:
- a binder that inherits configuration from this binder. Only exposed configuration on the returned binder will be visible to this binder.
- Since:
- 2.0
-
-