|
Generated by JDiff |
||||||||
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES |
This file contains all the changes in documentation in the packagecom.google.inject
as colored differences. Deletions are shownlike this, and additions are shown like this.
If no deletions or additions are shown in an entry, the HTML tags will be what has changed. The new HTML tags are shown in the differences. If no documentation existed, and then some was added in a later version, this change is noted in the appropriate class pages of differences, but the change is not shown on this page. Only changes in existing text are shown here. Similarly, documentation which was inherited from another class or interface is not shown here.
Note that an HTML error in the new documentation may cause the display of other documentation changes to be presented incorrectly. For instance, failure to close a <code> tag will cause all subsequent paragraphs to be displayed differently.
A support class for Modules which reduces repetition and resultsClass AbstractModule, void bindInterceptor(Matcher<Class<?>>, Matcher<Method>, MethodInterceptor[])inin a morereadablereadable configuration. Simply extend this class, implement .configure(), and call theinheritedinherited methods which mirror those foundinin Binder. For example:public class MyModule extends AbstractModule { protected void configure() { bind(Service.class).to(ServiceImpl.class).in(Singleton.class); bind(CreditCardPaymentService.class); bind(PaymentService.class).to(CreditCardPaymentService.class); bindConstant().annotatedWith(Names.named("port")).to(8080); } }@author crazybob@google.com (Bob Lee)
@see Binder#bindInterceptor(com.google.inject.matcher.Matcher, com.google.inject.matcher.Matcher,Class AbstractModule, void bindListener(Matcher<TypeLiteral<?>>, TypeListener)org.aopalliance.intercept.MethodInterceptor[])
@see Binder#bindListener(com.google.inject.matcher.Matcher,Class AbstractModule, Stage currentStage()com.google.inject.spi.TypeListener) @since 2.0
@see Binder#currentStage()Class AbstractModule, void requireBinding(Class<?>)@since 2.0
Adds a dependency from this module to {@code type}. When the injectorClass AbstractModule, void requireBinding(Key<?>)isis created, Guicewillwill report an error if {@code type} cannot be injected.Note that this requirement may besatisfiedsatisfied by implicit binding, suchasas a public no-arguments constructor. @since 2.0
Adds a dependency from this module to {@code key}. When the injectorisis created, Guicewillwill report an error if {@code key} cannot be injected.Note that this requirement may besatisfiedsatisfied by implicit binding, suchasas a public no-arguments constructor. @since 2.0
Collects configuration information (primarily bindings) which willClass Binder, void addError(String, Object[])bebe used to createanan Injector. Guice provides this object toyouryour application's Module implementorssoso they may eachcontributecontribute their own bindings and other registrations.The Guice Binding EDSL
Guice uses an embedded domain-specific language, or EDSL, to helpyouyou createbindingsbindings simply and readably.This approach is great foroveralloverall usability, but it does come with asmallsmall cost: it is difficulttoto learn how to use the Binding EDSL byreadingreading method-levellevel javadocs.Instead, you should consult the seriesofof examples below.To save space,thesethese examples omit theopeningopening {@code binder}, just as you will if your moduleextendsextends AbstractModule.bind(ServiceImpl.class);This statement does essentially nothing; it "binds the {@code ServiceImpl}class to itself"andand does not change Guice's default behavior.You maystillstill want to use this if you preferyouryour Module class to serve asanan explicit manifest for the services it provides.Also, in rare cases,Guice may be unable to validate a binding at injector creation time unlessit isit is given explicitly.bind(Service.class).to(ServiceImpl.class);Specifies that a request for a {@code Service} instance with nobindingbinding annotations shouldbebe treated as if it were a request foraa {@code ServiceImpl} instance. This overridesthethe function ofanyany @ImplementedBy or @ProvidedBy annotations found on {@code Service}, since Guice will havealreadyalready "moved on" to {@codecode ServiceImpl} before it reaches the point when itstartsstarts looking for these annotations.bind(Service.class).toProvider(ServiceProvider.class);In this example, {@code ServiceProvider} must extend orimplementimplement {@code Provider}. ThisThis binding specifies that Guice shouldresolveresolve an unannotated injection request for {@code Service} by first resolvinganan instance of {@code ServiceProvider} in the regular way, thencallingcalling get() on the resulting Provider instance to obtainthethe {@code Service} instance.The Provider you use here does not have to be a "factory";
thatthat is, a providerwhichwhich always creates each instance it provides.However, this is generally a good practicetoto follow.You can thenuseuse Guice's concept of scopes to guide when creationshouldshouldhappenhappen -- "letting Guice work for you".bind(Service.class).annotatedWith(Red.class).to(ServiceImpl.class);Like the previous example, but only applies to injection requests thatuseuse the bindingannotationannotation {@code @Red}.If your module also includesbindingsbindings for particular values ofthethe {@code @Red} annotation (see below),then this binding will serve as a "catch-all" for anyvaluesvalues of {@code @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 {@code ServiceImpl} classintointo singleton scope.Guicewillwill create only one instance of {@code ServiceImpl}and will reuse it for all injection requestsofof this type.Note that itisis still possible to bind another instance of {@code ServiceImpl} ifthethesecondsecond binding is qualified by an annotation as in the previous example.Guiceisis notoverlyoverly concerned with preventing you from creatingmultiplemultiple instances of your "singletons",onlyonly with enabling your applicationtoto share only one instance if that's all you tell Guiceyouyou need.Note: a scope specified in this way overrides any scope
thatthat was specifiedwithwith an annotation on the {@code ServiceImpl} class.Besides Singleton/Scopes.SINGLETON, there
areare servlet-specificscopesscopes availableinin {@code com.google.inject.servlet.ServletScopes}, and your Modulescancancontributecontribute 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.ItIt tells Guice howtoto honor an injection request for an element oftypetype {@code PaymentService}. The class {@code CreditCardPaymentService} must implement thethe {@code PaymentService} interface. Guice cannot currently bindoror inject a generic type, such as {@code Set}; all type parametersparameters mustbebe fully specified.bind(Service.class).toInstance(new ServiceImpl()); // or, alternatively bind(Service.class).toInstance(SomeLegacyRegistry.getService());In this example, your module itself, not Guice, takesresponsibilityresponsibility for obtainingaa {@code ServiceImpl} instance, then asks Guice to alwaysuseuse this single instance to fulfillallall {@code Service} injection requests.WhenWhen the Injector is created, it willautomaticallyautomatically performfieldfield and method injection for this instance, but any injectable constructoronon {@codecode ServiceImpl} is simply ignored.Note that using this approachresultsresults in "eager loading"behaviorbehavior that you can't control.bindConstant().annotatedWith(ServerHost.class).to(args[0]);Sets up a constant binding. Constant injections must always be annotated.When aconstantconstant binding's value is a string, it is eligile for conversiontoto all primitive types, to all enums, andtoto class literals.ConversionsConversions for other types canbebe configured using convertToTypes().{@literal @}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 bindingstoto differentspecificspecific values of your annotation.Getting your hands onthethe right instance of the annotation is a bitofof a pain -- one approach,shownshown above, is to apply a prototype annotation to a field in yourmodulemodule class,soso 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 providedaa standard annotation, @Named.Becauseofof Guice's library support, binding bynamename is quite easier than inthethe arbitrary binding annotation case we just saw.However, rememberthat thesethat these names will live in a single flat namespace with all the other names usedininyouryour application.ConstructorIn this example, we directly tell Guice which constructor to use in aloneCtor = getLoneCtorFromServiceImplViaReflection(); bind(ServiceImpl.class) .toConstructor(loneCtor); concreteconcreteclassclass implementation. It means that we do not need to place {@literal @}InjectInject on any ofthethe constructors and that Guice treats the provided constructor asthoughthough it were annotated so. Itisis useful for cases where you cannot modifyexistingexisting classes and is a bit simpler than usingaa Provider.The above list of examples is far from exhaustive.
If you can thinkofof how the concepts ofoneone example might coexist with the concepts from another,you can most likely weave the two together.If the two concepts makenono sense with each other, you most likely won't be able to do it.Ina fewa few cases Guice will let something bogus slip by, and will then inform youofof the problemsatat runtime, as soon as you try to create your Injector.The other methods of Binder such as .bindScope,
.bindInterceptor, .install, .requestStaticInjection,.addError and .currentStage arenotnot part of the Binding EDSL;you can learn how to use these in the usual way, from the method documentation. @author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson) @author kevinb@google.com (Kevin Bourrillion)
Records an error message which will be presented to the user at aClass Binder, void addError(Throwable)laterlater time. Unlikethrowingthrowing an exception, this enable us tocontinuecontinue configuring the Injector and discover more errors. Uses String.format(String, Object[]) to insert the arguments intothethe message.
Records an exception, the full details of which will be logged, andClass Binder, void bindInterceptor(Matcher<Class<?>>, Matcher<Method>, MethodInterceptor[])thethe message of whichwillwill be presented to the user at alaterlater time. If your Module calls something that you worrymaymay fail, youshouldshould catch the exception and pass it into this.
Binds method interceptor[s] to methods matched by class and method matchers. A method is eligible for interception if:Class Binder, void bindListener(Matcher<Binding<?>>, ProvisionListener[])@param classMatcher matches classes the interceptor should apply to.
- Guice created the instance the method is
onon- Neither the enclosing type nor the method is
finalfinal- And the method is package-private, protected, or
publicpublicForForexample: {@codecode only(Runnable.class)}. @param methodMatcher matches methods the interceptor should apply to.ForForexample: {@codecode annotatedWith(Transactional.class)}. @param interceptors to bind.The interceptors are called in the ordertheythey are given.
Registers listeners for provisioned objects. Guice will notifyClass Binder, void convertToTypes(Matcher<TypeLiteral<?>>, TypeConverter)thethe listeners just beforeandand after the object is provisioned.ProvisionedProvisioned objects that are also injectable (everythingeverything except objectsprovidedprovided through Providers) can also be notified throughTypeListenersTypeListeners registeredinin .bindListener.@param bindingMatcher that matches bindings of provisioned objects thelistenerlistenershould beshouldbenotified of @param listeners for provisioned objects matched bybindingMatcherbindingMatcher @since 4.0
Binds a type converter. The injector will use the given converterClass Binder, void disableCircularProxies()toto convert stringconstantsconstants to matching types as needed. @param typeMatcher matches types the converter can handle @param converter converts values @since 2.0
Prevents Guice from injecting dependencies that form a cycle, unless broken byClass Binder, Provider<T> getProvider(Class<T>)aa 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. @since 3.0
Returns the provider used to obtain instances for the given injection type.Class Binder, Provider<T> getProvider(Dependency<T>)Thereturnedreturned provider will not be valid until the Injector hasbeenbeen created. The provider willthrowthrow an {@code IllegalStateException} ifyouyou try to use it beforehand. @since 2.0
Returns the provider used to obtain instances for the given injection key.Class Binder, Provider<T> getProvider(Key<T>)Thereturnedreturned provider will be attached to the injection point andwillwill follow the nullability specifiedinin the dependency.Additionally, the returned provider will not be valid until the Injectorhas been created. The provider will throw an {@code IllegalStateException} ifyou tryyou try to use it beforehand. @since 4.0
Returns the provider used to obtain instances for the given injection key.Class Binder, PrivateBinder newPrivateBinder()Thereturnedreturned provider will not be valid until the Injector hasbeenbeen created. The provider willthrowthrow an {@code IllegalStateException} ifyouyou try to use it beforehand. @since 2.0
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 PrivateModule for details. @return a binder that inherits configuration from this binder. Only exposed configuration onClass Binder, void requestInjection(Object)the returned binder will be visible to this binder. @since 2.0
Upon successful creation, the Injector will inject instanceClass Binder, void requestInjection(TypeLiteral<T>, T)fieldsfields and methods ofthethe given object. @param instance for which members will be injected @since 2.0
Upon successful creation, the Injector will inject instanceClass Binder, void requestStaticInjection(Class[])fieldsfields and methods ofthethe given object. @param type of instance @param instance for which members will be injected @since 2.0
Upon successful creation, the Injector will inject staticClass Binder, void requireAtInjectOnConstructors()fieldsfields and methods inthethe given classes. @param types for which static members will be injected
Requires that a {@literal @}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 {@literal @}Inject annotation exists on any constructor.Class Binder, void requireExactBindingAnnotations()
If the class is bound using LinkedBindingBuilder.toConstructor, Guice willstill injectstill inject that constructor regardless of annotations. @since 4.0
Requires that Guice finds an exactly matching binding annotation.Class Binder, void requireExplicitBindings()This disablesthethe error-proneprone feature in Guice where it can substitute a bindingforfor{@literal @}Named Foo
whenwhen attempting toinjectinject{@literal @}Named("foo") Foo
. @since 4.0
Instructs the Injector that bindings must be listed in a Module in orderClass Binder, Binder skipSources(Class[])toto be injected. Classes that are not explicitly bound in a module cannotbebe injected. Bindings createdthroughthrough a linkedbindingbinding (bind(Foo.class).to(FooImpl.class)
) are allowed, butthetheimplicitimplicit binding (FooImpl
) cannot be directly injectedunlessunless it is also explicitly bound (bind(FooImpl.class)
).
Tools can still retrieve bindings for implicit bindings (bindingscreatedcreated through alinkedlinked binding) if explicit bindings are required,howeverhowever Binding.getProvider will fail.
By default, explicit bindings are not required.
If a parent injector requires explicit bindings, then all childinjectorsinjectors (andprivateprivate modules within that injector) also require explicit bindings.If a parent does notrequirerequire explicit bindings, a child injector orprivateprivate module may optionally declare itselfasas requiring explicit bindings. Ifitit does, the behavior is limited only to that child oranyany grandchildren.NoNo siblings of the child will require explicit bindings.
In the absence of an explicit binding for the target, linked bindingsinin childinjectorsinjectors create a binding for the target in the parent. Sincethisthis behavior can be surprising, itcausescauses an error instead if explicitbindingsbindings are required. To avoid this error, add anexplicitexplicit binding for the target,either in the child or the parent.@since 3.0
Returns a binder that skips {@code classesToSkip} when identifyClass Binder, Binder withSource(Object)thethe calling code. The caller'ss StackTraceElement is used tolocatelocate the source of configuration errors. @param classesToSkip library classes that create bindings on behalfofof their clients. @return a binder that shares its configuration with this binder. @since 2.0
Returns a binder that uses {@code source} as the reference locationforfor configuration errors. This is typically a StackTraceElementfor {@code .java} source but it could anybindingbinding source, such asthethe path to a {@code .properties} file. @param source any object representing the source location and hasaa concise toString() value @return a binder that shares its configuration with this binder @since 2.0
A mapping from a key (type and optional annotation) to the strategy for getting instances of the type. This interface is part of the introspection API and is intended primarily for use byClass Binding, Provider<T> getProvider()tools.Bindings are created in several ways:
- Explicitly in a module, via {@code bind()} and {@code bindConstant()}
statements:statements:bind(Service.class).annotatedWith(Red.class).to(ServiceImpl.class); bindConstant().annotatedWith(ServerHost.class).to(args[0]);- Implicitly by the Injector by following a type's
pointer annotations or by using its annotatedoror default constructor.- By converting a bound instance to a different type.
- For providers, by delegating to the binding for the provided type.
They exist on both modules and on injectors, and their behaviour is different for each:
@param
- Module bindings are incomplete and cannot be used to provide instances.
ThisThisis because the applicable scopes and interceptors may not be known until aninjectorinjector isiscreated. From a tool's perspective, module bindings are like the injector'ssourcesource code. Theycode.Theycan be inspected or rewritten, but this analysis must be done statically.- Injector bindings are complete and valid and can be used to provide
instances. From a tools' perspective, injector bindings are like reflection foranan injector.injector.They have full runtime information, including the complete graph ofinjectionsinjectionsnecessary tonecessarytosatisfy a binding.the bound type. The injected is always assignable to this type. @author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson)
Returns the scoped provider guice uses to fulfill requests forthisthis binding. @throws UnsupportedOperationException when invoked on a Bindingcreated via com.google.inject.spi.Elements.getElements.ThisThis method is only supported on Bindings returned from an injector.
Annotates annotations which are used for binding. Only one suchannotationannotation may apply to asinglesingle injection point. You must also annotatebinderbinder annotations with {@code @Retention(RUNTIME)}.ForFor example:{@code @}Retention(RUNTIME) {@code @}Target({ FIELD, PARAMETER, METHOD }) {@code @}BindingAnnotation public {@code @}interface Transactional {}@author crazybob@google.com (Bob Lee)
Returns a value that was only partially computed due to this exception. The caller canuse thisuse this while collecting additional configuration problems. @return the partial value, or {@code null} if none was set. The type of the partial value isspecified by the throwing method.
The entry point to the Guice framework. Creates InjectorsClass Guice, Injector createInjector(Iterable<Module>)fromfrom Modules.Guice supports a model of development that draws clear boundaries
betweenbetween APIs, Implementations of these APIs, Modules which configurethesethese implementations, andfinallyfinally Applications which consist of a collectionofof Modules. It is the Application, whichtypicallytypically defines your {@code main()}method, that bootstraps the Guice Injector using the {@code Guice} class,asas in this example:public class FooApplication { public static void main(String[] args) { Injector injector = Guice.createInjector( new ModuleA(), new ModuleB(), . . . new FooApplicationFlagsModule(args) ); // Now just bootstrap the application and you're done FooStarter starter = injector.getInstance(FooStarter.class); starter.runApplication(); } }
Creates an injector for the given set of modules. This is equivalentClass Guice, Injector createInjector(Module[])toto calling .createInjector(Stage, Iterable) with Stage.DEVELOPMENT. @throws CreationException if one or more errors occur duringinjectorinjector creation
Creates an injector for the given set of modules. This is equivalentClass Guice, Injector createInjector(Stage, Iterable<Module>)toto calling .createInjector(Stage, Module...) with Stage.DEVELOPMENT. @throws CreationException if one or more errors occur duringinjectorinjector construction
Creates an injector for the given set of modules, in a givenClass Guice, Injector createInjector(Stage, Module[])developmentdevelopment stage. @throws CreationException if one or more errors occur duringinjectorinjector construction
Creates an injector for the given set of modules, in a givendevelopmentdevelopment stage. @throws CreationException if one or more errors occur duringinjectorinjector creation.
Annotates members of your implementation class (constructors,methodsmethods and fields) into whichthethe Injector should inject values.The Injector fulfills injection requests for:In all cases, a member can be injected regardless of its Java
- Every instance it constructs. The class being constructed must
havehave exactly one ofitsits constructors marked with {@code @Inject} or must haveaa constructor taking no parameters.TheThe Injector then proceeds toperformperform field and method injections.- Pre-constructed instances passed to Injector.injectMembers,
com.google.inject.binder.LinkedBindingBuilder.toInstance(Object)andand com.google.inject.binder.LinkedBindingBuilder.toProvider(javax.inject.Provider).Inthisthis case all constructors are, of course, ignored.- Static fields and methods of classes which any Module
hashas specificallyrequestedrequested static injection for,usingusing Binder.requestStaticInjection.accessaccess specifier (private, default, protected, public). @author crazybob@google.com (Bob Lee)
Returns a new injector that inherits all state from this injector. All bindings, scopes, interceptors and type converters are inherited -- they are visible to the child injector. Elements of the child injector are not visible to its parent.Class Injector, Map<Key<?>, Binding<?>> getAllBindings()Just-in-time bindings created for child injectors will be created in an ancestor injector whenever possible. This allows for scoped instances to be shared between injectors. Use explicit bindings to prevent bindings from being shared with the parent injector.
Optional injections in just-in-time bindings (created in the parent injector) may besilentlysilently ignoredifif the optional dependencies are from the child injector.No key may be bound by both an injector and one of its ancestors. This includes just-in-time bindings. The lone exception is the key for {@code Injector.class}, which is bound by each injector to itself. @since 2.0
Returns a snapshot of this injector's bindings, both explicit and just-in-time. The returned map is immutable; it contains only the bindings that were present when {@code getAllBindings()} was invoked. Just-in-time bindings are only present if they have been requested at least once. Subsequent calls may return a mapClass Injector, Map<Key<?>, Binding<?>> getBindings()with additionalwith additional just-in-time bindings.The returned map does not include bindings inherited from a parent injector, should one exist.
This method is part of the Guice SPI and is intended for use by tools and extensions.
@since 3.0
Returns this injector's explicit bindings.Class Injector, Binding<T> getExistingBinding(Key<T>)The returned map does not include bindings inherited from a parent injector, should one exist. The returned map is guaranteed to iterate (for example,
with itswith its Map.entrySet() iterator) in the order of insertion. In other words, the orderininwhichwhich bindings appear in user Modules.This method is part of the Guice SPI and is intended for use by tools and extensions.
Returns the binding if it already exists, or null if does not exist.Class Injector, MembersInjector<T> getMembersInjector(Class<T>)UnlikeUnlike .getBinding(Key), this does not attempt to create just-in-timebindingsbindings for keys that aren'tt bound.
This method is part of the Guice SPI and is intended for use by tools and extensions.@since 3.0
Returns the members injector used to inject dependencies into methods and fields on instances of the given type {@code T}. When feasible, use Binder.getMembersInjector(TypeLiteral) instead to get increased up front error detection. @param type type to get members injector for @see Binder#getMembersInjector(Class) for an alternative that offers up frontClass Injector, MembersInjector<T> getMembersInjector(TypeLiteral<T>)errorerror detection @since 2.0
Returns the members injector used to inject dependencies into methods and fields on instances of the given type {@code T}. @param typeLiteral type to get members injector for @see Binder#getMembersInjector(TypeLiteral) for an alternative that offers up front error detection @since 2.0Class Injector, Provider<T> getProvider(Class<T>)
Returns the provider used to obtain instances for the given type. When feasible,Class Injector, Map<Class<Annotation>, Scope> getScopeBindings()avoid usingavoid using this method, in favor of having Guice inject your dependencies ahead of time. @throws ConfigurationException if this injector cannot find or create the provider. @see Binder#getProvider(Class) for an alternative that offers up front error detection
Returns a map containing all scopes in the injector. The maps keys are scopingClass Injector, Set<TypeConverterBinding> getTypeConverterBindings()annotations likeannotations like {@code Singleton.class}, and the values are scope instances, such as {@codecode Scopes.SINGLETON}. The returned map is immutable.This method is part of the Guice SPI and is intended for use by tools and extensions.
@since 3.0
Returns a set containing all type converter bindings in the injector. The returned set is immutable.Class Injector, void injectMembers(Object)This method is part of the Guice SPI and is intended for use by tools and extensions.
@since 3.0
Injects dependencies into the fields and methods of {@code instance}. Ignores the presence or absence of an injectable constructor.Whenever Guice creates an instance, it performs this injection automatically (after first performing constructor injection), so if you're able to let Guice create all your objects for you, you'll never need to use this method. @param instance to inject members
onon @see Binder#getMembersInjector(Class) for a preferred alternative that supports checks before run time
Binding key consisting of an injection type and an optional annotation.Class Key, constructor Key()Matches the typeandand annotation at a point of injection.For example, {@code Key.get(Service.class, Transactional.class)}
willwill match:{@literal @}Inject public void setService({@literal @}Transactional Service service) { ... }{@code Key} supports generic types via subclassing just like TypeLiteral.
Keys do not differentiate between primitive types (int, char, etc.)
andand theircorrespondingcorresponding wrapper types (Integer, Character, etc.).PrimitivePrimitive types will be replaced with theirwrapperwrapper types when keys are created. @author crazybob@google.com (Bob Lee)
Constructs a new key. Derives the type from this class's type parameter.Class Key, constructor Key(Annotation)Clients create an empty anonymous subclass. Doing so embeds the
typetype parameter inthethe anonymous class's type hierarchy so we can reconstituteitit at runtime despite erasure.Example usage for a binding of type {@code Foo}:
{@code new Key
() {}}.
Constructs a new key. Derives the type from this class's type parameter.Class Key, constructor Key(Class<Annotation>)Clients create an empty anonymous subclass. Doing so embeds the
typetype parameter inthethe anonymous class's type hierarchy so we can reconstituteitit at runtime despite erasure.Example usage for a binding of type {@code Foo} annotated
withwith {@code @Bar}:{@code new Key
(new Bar()) {}}.
Constructs a new key. Derives the type from this class's type parameter.Class Key, Key<T> ofType(Class<T>)Clients create an empty anonymous subclass. Doing so embeds the
typetype parameter inthethe anonymous class's type hierarchy so we can reconstituteitit at runtime despite erasure.Example usage for a binding of type {@code Foo} annotated
withwith {@code @Bar}:{@code new Key
(Bar.class) {}}.
Returns a new key of the specified type with the same annotation asClass Key, Key<?> ofType(Type)thisthis key. @since 3.0
Returns a new key of the specified type with the same annotation asClass Key, Key<T> ofType(TypeLiteral<T>)thisthis key. @since 3.0
Returns a new key of the specified type with the same annotation asClass Key, Key<T> withoutAttributes()thisthis key. @since 3.0
Returns this key without annotation attributes, i.e. with onlythethe annotation type. @since 3.0
Injects dependencies into the fields and methods on instances of type {@code T}. Ignores the presence or absence of an injectable constructor. @paramtype to inject members ofof @author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson) @since 2.0
A module contributes configuration information, typicallyinterfaceinterface bindings, which will beusedused to create an Injector. A Guice-basedbased application is ultimately composed of littlemoremore than a setofof {@code Module}s and some bootstrapping code.Your Module classes can use a more streamlined syntax by
extendingextending AbstractModule rather than implementing this interface directly.In addition to the bindings configured via .configure,
bindingsbindings will be createdforfor all methods annotated with {@literal @}Provides.Use scope and binding annotationsonon these methods to configurethethe bindings.
Thrown from Provider.get when an attempt is made to access ascopedscoped object whilethethe scope in question is not currently active. @author kevinb@google.com (Kevin Bourrillion) @since 2.0
Returns a binder whose configuration information is hidden from its environment by default. See PrivateModule for details.Class PrivateBinder, AnnotatedElementBuilder expose(Class<?>)@author jessewilson@google.com (Jesse Wilson) @since 2.0
Makes a binding for {@code type} available to the enclosing environment. Use annotatedWith()toto expose {@code type} withaa binding annotation.
A module whose configuration information is hidden from its environment by default. Only bindings that are explicitly exposed will be available to other modules and to the users of the injector. This module may expose the bindings it creates and the bindings of the modules it installs.Class PrivateModule, void bindInterceptor(Matcher<Class<?>>, Matcher<Method>, MethodInterceptor[])A private module can be nested within a regular module or within another private module using install().
Its bindings live in a new environment that inherits bindings, type converters, scopes, and interceptors from the surrounding ("parent") environment.When you nest multiple private modules, the result is a tree of environments where the injector's environment is the root.Guice EDSL bindings can be exposed with expose(). {@literal @}Provides bindings can be exposed with the {@literal @}Exposed annotation:
public class FooBarBazModule extends PrivateModule { protected void configure() { bind(Foo.class).to(RealFoo.class); expose(Foo.class); install(new TransactionalBarModule()); expose(Bar.class).annotatedWith(Transactional.class); bind(SomeImplementationDetail.class); install(new MoreImplementationDetailsModule()); } {@literal @}Provides {@literal @}Exposed public Baz provideBaz() { return new SuperBaz(); } }Private modules are implemented using parent injectors. When it can satisfy their dependencies, just-in-time bindings will be created in the root environment. Such bindings are shared among all environments in the tree.
The scope of a binding is constrained to its environment. A singleton bound in a private module will be unique to its environment. But a binding for the same type in a different private module will yield a different instance.
A shared binding that injects the {@code Injector} gets the root injector, which only has access to bindings in the root environment. An explicit binding that injects the {@code Injector} gets access to all bindings in the child environment.
To promote a just-in-time binding to an explicit binding, bind it:
bind(FooImpl.class);@author jessewilson@google.com (Jesse Wilson) @since 2.0
@see Binder#bindInterceptor(com.google.inject.matcher.Matcher, com.google.inject.matcher.Matcher, org.aopalliance.intercept.MethodInterceptor[])Class PrivateModule, void convertToTypes(Matcher<TypeLiteral<?>>, TypeConverter)
@see Binder#convertToTypes(com.google.inject.matcher.Matcher, com.google.inject.spi.TypeConverter)
An object capable of providing instances of type {@code T}. Providers are used in numerous ways by Guice:Class Provider, T get()@param
- When the default means for obtaining instances (an injectable or parameterless constructor) is insufficient for a particular binding, the module can specify a custom {@code Provider} instead, to control exactly how Guice creates or obtains instances for the binding.
- An implementation class may always choose to have a {@code Provider
} instance injected, rather than having a {@code T} injected directly. This may give you access to multiple instances, instances you wish to safely mutate and discard, instances which are out of scope (e.g. using a {@code @RequestScoped} object from within a {@code @SessionScoped} object), or instances that will be initialized lazily.- A custom Scope is implemented as a decorator of {@code Provider
}, which decides when to delegate to the backing provider and when to provide the instance some other way. - The Injector offers access to the {@code Provider
} it uses to fulfill requestsrequestsforfor a given key, via the Injector.getProvider methods.the type of object this providesprovides @author crazybob@google.com (Bob Lee)
Provides an instance of {@code T}.Must never return {@code null}.@throws OutOfScopeException when an attempt is made to access a scoped object while the scope in question is not currently active @throws ProvisionException if an instance cannot be provided. Such exceptions include messages and throwables to describe why provision failed.
Indicates that there was a runtime failure while providing an instance.@author kevinb@google.com (Kevin Bourrillion) @author jessewilson@google.com (Jesse Wilson) @since 2.0
A scope is a level of visibility that instances provided by Guice may have.Class Scope, Provider<T> scope(Key<T>, Provider<T>)By default,anan instance created by the Injector has no scope,meaning it has no state fromthethe framework's perspective --thethe {@code Injector} creates it, injects it once into the classthatthat required it,and then immediately forgets it. Associating a scope with aparticular bindingparticular binding allows the created instance to be "remembered" and possiblyusedused again for other injections.An example of a scope is Scopes.SINGLETON. @author crazybob@google.com (Bob Lee)
Scopes a provider. The returned provider returns objects from this scope.Class Scope, String toString()If an object doesnotnot exist in this scope, the provider can use thegivengiven unscoped provider to retrieve one.Scope implementations are strongly encouraged to
overrideoverride Object.toString inthethe returned provider and include thebackingbacking provider's {@code toString()} output. @param key binding key @param unscoped locates an instance when one doesn't already exist inthisthis scope. @return a new provider which only delegates to the given unscopedproviderprovider when an instanceofof the requested object doesn't already exist inthisthis scope
A short but useful description of this scope.For comparison, thestandardstandard scopes thatshipship with guice use thedescriptionsdescriptions {@code "Scopes.SINGLETON"}, {@code "ServletScopes.SESSION"} and {@code "ServletScopes.REQUEST"}.
Annotates annotations which are used for scoping. Only one suchannotationannotation may apply to asinglesingle implementation class. You must also annotatescopescope annotations with {@code @Retention(RUNTIME)}. For example:{@code @}Retention(RUNTIME) {@code @}Target(TYPE, METHOD) {@code @}ScopeAnnotation public {@code @}interface SessionScoped {}@author crazybob@google.com (Bob Lee)
Returns true if the object is a proxy for a circular dependency,Class Scopes, Scope NO_SCOPEconstructed by Guicebecausebecause it encountered a circular dependency.ScopeScope implementations should be careful to notcachecache circular proxies,because the proxies are not intended for general purpose use. (They are designed just to fulfill the immediate injection, not all injections.Caching them can leadtoto IllegalArgumentExceptions or ClassCastExceptions.) @since 4.0
No scope; the same as not applying any scope at all.Each timethethe Injector obtains aninstanceinstance of an object with "no scope", it injectsthisthis instance then immediately forgets it.Whenthethe next request for thesamesame binding arrives it will need to obtain the instance over again.This exists only in case a class has been annotated with a
scopescope annotation such as @Singleton, and you need tooverrideoverride this to "no scope" in your binding. @since 2.0
Apply this to implementation classes when you want only oneinstanceinstance (per Injector) tobebe reused for all injections for that binding. @author crazybob@google.com (Bob Lee)
Represents a generic type {@code T}. Java doesn't yet provide a wayClass TypeLiteral, constructor TypeLiteral()toto represent generic types, so this class does. Forces clients to createaa subclass of this class which enables retrieval of the type information evenatat runtime.For example, to create a type literal for {@code List
}, you cancan create anemptyempty anonymous inner class:
{@code TypeLiteral> list = new TypeLiteral
>() {};}
Along with modeling generic types, this class can resolve type parameters.
For example,toto figure out what type {@code keySet()} returns on a {@codecode Map}, use this code: {@@author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson)codecode TypeLiteral
Constructs a new type literal. Derives represented class fromClass TypeLiteral, Class<? super T> getRawType()typetype parameter.Clients create an empty anonymous subclass. Doing so embeds the
typetype parameter inthethe anonymous class's type hierarchy so we can reconstituteitit at runtime despite erasure.
Returns the raw (non-generic) type for this type.@since 2.0