|
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 results in a more readable configuration. Simply extend this class, implement .configure(), and call the inherited methods which mirror those found in Binder. For example:@author crazybob@google.com (Bob Lee)import static com.google.inject.Names.named;public class MyModule extends AbstractModule { protected void configure() { bind(FooService.class).to(FooImplServiceImpl.class).in(ScopesSingleton.SINGLETONclass); bind(BarImplCreditCardPaymentService.class);linkbind(BarPaymentService.class).to(BarImplCreditCardPaymentService.class); bindConstant().annotatedWith(Names.named("port")).to(8080); } }
Collects configuration information (primarily bindings) which will be used to create an Injector. Guice provides this object to your application's ModuleClass Binder, AnnotatedBindingBuilder<T> bind(Class<T>)simplementors 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 bindingscontributedsimply 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 {@codeModulebinder}s,definejusthowas you will if your module extends AbstractModule.bind(ServiceImpl.class);
This statement does essentially nothing; it "binds the {@code Injectorcode ServiceImpl} class to itself" and does not change Guice'sresolves dependenciesdefault behavior.AYou may still want to use this if you prefer yourKeyModuleconsistingclassofto serve as an explicit manifest for the services it provides. Also, in rare cases, Guice may be unable to validate atype and optionalbinding at injectorannotationcreation time unless it is given explicitly.bind(Service.class).to(ServiceImpl.class);Specifies thatuniquelya request for a {@code Service} instance with noidentifiesbinding annotations should be treated as if it were a request for a {@code ServiceImpl} instance. This overrides the function of any @ImplementedBy or @ProvidedBy annotations found on {@code Service}, since Guice will have already "moved on" to {@code ServiceImpl} before it reaches the point when it starts looking for these annotations.bind(Service.class).toProvider(ServiceProvider.class);In this example, {@code ServiceProvider} must extend or implement {@code Provider}. This bindingwithinspecifies that Guice should resolve an unannotated injection request for {@codecodeInjectorService} by first resolving an instance of {@code ServiceProvider} in the regular way, then calling get() on the resulting Provider instance to obtain the {@code Service} instance.
YouThemayProviderbind fromyou useahere does notkeyhave to:beAnotherabinding"factory"; that is, a provider which always creates each instance it provides. However, thisbindingis generally a good practice to follow. You can then use Guice'skey isconcept ofnowscopes to guide when creation should happen -- "aliasedlettingtoGuice work for you".Anotherbind(Service.class).annotatedWith(Red.class).to(ServiceImpl.class); Like the previous example, but only applies to injection requests that use the binding annotation {@code @Red}. If your module also includes bindings for particular values of the {@code @Red} annotation (see below),whichthen this bindingreferenceswill serve as aProvider"catch-all" for any values 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} class into singleton scope. Guice will create only one instance of {@code ServiceImpl} and will reuse it for all injection requests of thiskeytype.ANotepreconstructed instancethat itAispreconstructedstill possible to bind another instancewhichofshould{@codebeServiceImpl}usedif 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 {@code ServiceImpl} class.
ProviderSingleton/Scopes.SINGLETON, there are servlet-specific scopes available in {@code com.google.inject.servlet.ServletScopes}, and your Modules can contribute their own custom scopes forthis bindinguse here as well.InThis admittedly odd construct is the way to bind aaddition,bind(new TypeLiteral<PaymentService<CreditCard>>() {}) .to(CreditCardPaymentService.class);bindingparameterizedmaytype.haveIt tells Guice how to honor anassociatedinjectionscoperequest for an element of type {@code PaymentService}. The class {@code CreditCardPaymentService} must implement the {@code PaymentService , such} interface. Guice cannot currently bind or inject a generic type asasScopes{@code Set}; all type parameters must be fully specified .SINGLETONbind(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 {@code ServiceImpl} instance, then asks Guice to always use this single instance to fulfill all {@code Service} injection requests. When the Injector is created, it will automatically perform field andsingleton bindingsmethod injectionmayfor this instance, but any injectable constructor on {@code ServiceImpl} is simply ignored.specifyNote that using this approach results in "eagerorloading" behavior that youlazycan'tinitializationcontrol.SeeSets up a constant binding. Constant injections must always be annotated. When a constantthebindConstant().annotatedWith(ServerHost.class).to(args[0]);usersbinding'sguidevalue is a string, it is eligile for conversion to all primitive types, toappendixall enums, and to class literals. Conversions for other types can be configured using convertToTypes().{@literal @}Color("red") Color red; // A member variable (field) . . . red = MyModule.class.getDeclaredField("red"How).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 theInjector resolves injectionannotation is arequestsbit 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 abetter understandcommon 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 bindingresolutionannotation 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.AfterIn this example, we directly tell Guice which constructor to use in a concrete class implementation. It means that we do not need to place {@anConstructorloneCtor = getLoneCtorFromServiceImplViaReflection(); bind(ServiceImpl.class) .toConstructor(loneCtor); code Injectorliteral @}Injecthas beenon anycreated,ofits bindings maythe constructors andbethat 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 bitexaminedsimpler 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
methodslikeof Binder such asInjector.getBinding(Key)bindScope,but.bindInterceptor,this.install,read-only.requestStaticInjection,Binding.addErrortypeandis.currentStage are notused whenpart ofcreatingthetheBindingbindingsEDSL; 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)
Class Binder, LinkedBindingBuilder<T> bind(Key<T>)Creates a binding to aSee the EDSL examples attypeBinder.
Class Binder, AnnotatedBindingBuilder<T> bind(TypeLiteral<T>)Creates a binding to aSee the EDSL examples atkeyBinder.
Class Binder, AnnotatedConstantBindingBuilder bindConstant()Creates a binding to aSee the EDSL examples attypeBinder.
Class Binder, void bindInterceptor(Matcher<Class<?>>, Matcher<Method>, MethodInterceptor[])Binds a constant value toSee the EDSL examples atan annotationBinder.
Bindsamethod interceptor[s] to methods matched by class andmethodmethod matchers. A method is eligible for interception if:@param classMatcher matches classes the interceptor should apply to. For example: {@code only(Runnable.class)}. @param methodMatcher matches methods the interceptor should apply to. For example: {@code annotatedWith(Transactional.class)}. @param interceptors to bind
- Guice created the instance the method is on
- Neither the enclosing type nor the method is final
- And the method is package-private, protected, or public
A mapping from a key (type and optional annotation) toClass Binding, Provider<T> getProvider()atheproviderstrategy forofgetting instances ofthatthe type.This interface is part of theInjectorintrospection API and is intendedprimaryprimarily for use by tools.Bindings are created in several ways:
- Explicitly in a module, via {@code bind()} and {@code bindConstant()} 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 annotated or 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:
tools' perspective, injector bindings are like reflection for an injector. They have full runtime information, including the complete graph of injections necessary to satisfy a binding. @param
- Module bindings are incomplete and cannot be used to provide instances. This is because the applicable scopes and interceptors may not be known until an injector is created. From a tool's perspective, module bindings are like the injector's source code. They can 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
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 Binding created via com.google.inject.spi.Elements.getElements. This method is only supported on Bindings returned from an injector.
Annotates annotations which are used for binding. Only one such annotation
may apply to a single injection point. You must also annotate binder
annotations with {@code @Retention(RUNTIME)}. For example:
{@code @}Retention(RUNTIME)
{@code @}Target({ FIELD, PARAMETER, METHOD })
{@code @}BindingAnnotation
public {@code @}interface Transactional {}
@author crazybob@google.com (Bob Lee)
Thrown when errors occur while creating a Injector. Includes aClass CreationException, constructor CreationException(Collection<Message>)listlist ofencounteredencountered errors.Typically, a clientClients should catch this exception,loglog it, and stop execution. @author crazybob@google.com (Bob Lee)
Class CreationException, Collection<Message> getErrorMessages()ConstructsCreates anewCreationExceptionexceptioncontainingfor{@codethe given errorsmessages}.
Gets the error messages which resulted inReturns messages for the errors that caused this exception.
The entry point to the Guice framework. Creates Injectors from Modules. For advanced usage, see InjectorBuilder.Class Guice, Injector createInjector(Module[])Guice supports a model of development that draws clear boundaries between APIs, Implementations of these APIs, Modules which configure these implementations, and finally Applications which consist of a collection of Modules. It is the Application, which typically defines your {@code main()} method, that bootstraps the Guice Injector using the {@code Guice} class, as 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. To create an injector with a Stage or other options, see InjectorBuilder. @throws CreationExceptionClass Guice, Injector createInjector(Stage, Module[])from which you can retrieveif one or more errorstheoccur during injectorindividualerrormessagesconstruction
Creates an injector for the given set of modules, in a given development stage. Use InjectorBuilder for advanced injector creation. @throws CreationExceptionfrom which you can retrieveif one or more errorstheoccur during injectorindividualerrormessagescreation.
Class Injector, List<Binding<T>> findBindingsByType(TypeLiteral<T>)FulfillsBuildsrequests fortheobjectgraphsinstancesof objects that make up your application,.always ensuring that these instances are properly injected before they areThe injector tracks the dependencies for each type and uses bindingsreturned.toTheinject{@codethem.Injector}This is theheartcore oftheGuiceframework,although youdon't typicallyrarely interact with it directlyvery often.ThisThis "behind-the-scenes" operation is what distinguishesthedependency injectionpatternfrom its cousin, the service locator. The {@code Injector} API has a few additional features: it allows pre-constructed instances to have their fields andmethods injected and offers programmatic introspection to support tool developmentpattern.Contains several default bindings:
Injectors are created using the facade class Guice.
- This Injector instance itself
- A {@code Provider
} for each binding of type {@code T} - The java.util.logging.Logger for the class being injected
- The Stage in which the Injector was created
An injector can also inject the dependencies of already-constructed instances. This can be used to interoperate with objects created by other frameworks or services.
Injectors can be hierarchical. Child injectors inherit the configuration of their parent injectors, but the converse does not hold.
The injector's internal bindings are available for introspection. This enables tools and extensions to operate on an injector reflectively.
@author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson)
Class Injector, Binding<T> getBinding(Key<T>)FindsReturns all explicit bindingstofor {@code type}.This method is part of
thegivenGuicetypeSPI and is intended for use by tools and extensions.
Class Injector, Map<Key<?>, Binding<?>> getBindings()Gets aReturns the binding for the given injection key. This will be an explicit bindings if the key was bound explicitly by a module, or an implicit binding otherwise. The implicit binding will be created if necessary.This method is part of the Guice SPI and is intended for use by tools and extensions. @throws ConfigurationException if this injector cannot find or create the binding.
Class Injector, T getInstance(Class<T>)Gets allReturns this injector's explicit bindings.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 its Map.entrySet() iterator)
in the order of insertion. In other words, the order in which bindings appear in user Modules.This method is part of the Guice SPI and is intended for use by tools and extensions
.
Class Injector, T getInstance(Key<T>)Gets an instance bound toReturns the appropriate instance for the given injection type; equivalenttoto {@codecode getProvider(type).get()}. When feasible, avoid 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. @throws ProvisionException if there was a runtime failure while providing an instance.
Class Injector, Provider<T> getProvider(Class<T>)Gets an instance bound toReturns the appropriate instance for the given injection key; equivalenttoto {@codecode getProvider(key).get()}. When feasible, avoid 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. @throws ProvisionException if there was a runtime failure while providing an instance.
Class Injector, Provider<T> getProvider(Key<T>)GetsReturns the providerboundused to obtain instances for the given type. When feasible, avoid 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
Class Injector, void injectMembers(Object)GetsReturns the providerboundused to obtain instances for the given injection key. When feasible, avoid 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(Key) for an alternative that offers up front error detection
Injects dependencies into the fields and methods of {@code instance}. Ignores the presence or absence of anexisting objectinjectable constructor.DoesWhenever
not injectGuice createsthean 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 on @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. Matches the type and annotation at a point of injection.For example, {@code Key.get(Service.class, Transactional.class)} will 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.) and their correpsonding wrapper types (Integer, Character, etc.). Primitive types will be replaced with their wrapper types when keys are created. @author crazybob@google.com (Bob Lee)
A module contributes configuration information, typically interface bindings, which will be used to create an Injector. AClass Module, void configure(Binder)guiceGuice-based application is ultimately composed of little more than a set of {@code Module}s and some bootstrapping code.Your Module classes can use a more streamlined syntax by extending AbstractModule rather than implementing this interface directly.
In addition to the bindings configured via .configure, bindings will be created for all methods annotated with {@literal @}Provides. Use scope and binding annotations on these methods to configure the bindings.
Contributes bindings and other configurationstofor thisamodule to {@codeBinderbinder}.Do not invoke this method directly to install submodules. Instead use Binder.install(Module), which ensures that provider methods are discovered.
Class Provider, T get()Simply, anyAn object capable of providing instances of type {@code T}.Providers are used in numerouswaysways bytheGuiceframework:@param
- When the default means for obtaining instances (an injectable
oror parameterless constructor) is insufficient for a particular binding,thethe module can specify a custom {@code Provider} instead, to control exactlyhowhow 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.ThisThis may give you access tomultiplemultiple instances, instances you wish tosafelysafely mutate and discard, instances which are out ofscopescope (e.g. usingaa {@code @RequestScoped} object from within a {@code @SessionScoped} object),oror instancesyou don't want to initializethatuntil theywill beare absolutelyinitializedneededlazily.- A custom Scope is implemented as a decorator
ofof {@code Provider}, which decidesdecides when to delegate to the backingproviderprovider and when to provide the instance some other way.- The Injector offers access to the {@code Provider
} it usesuses to fulfillrequestsrequests for a given key, via the Injector.getProvidermethods.the type of object this providerprovides @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.
A scope is a level of visibility that instances provided by Guice may have. By default, an instance created by the Injector hasClass Scope, Provider<T> scope(Key<T>, Provider<T>)nono scope, meaning it has no state from the framework's perspective -- the {@code Injector} creates it, injects it once into the class that required it, and then immediately forgets it. Associating a scope with aparticular bindingparticular binding allows the created instance to be "remembered" and possiblyusedused againforfor other injections.@seeAn example of a scope is Scopes
#SINGLETON.SINGLETON. @author crazybob@google.com (Bob Lee)
Scopes a provider. The returnedlocatorprovider returns objects from this scope.IfIf an object does not exist in this scope, the provider can use the given unscoped provider to retrieve one.Scope implementations are strongly encouraged to override Object.toString in the returned provider and include the backing provider's {@code toString()} output. @param key binding key @param unscoped locates an instance when one doesn't already exist in this scope. @return a new provider which only delegates to the given unscoped provider when an instance of the requested object doesn't already exist in this scope
Annotates annotations which are used for scoping. Only one such annotation
may apply to a single implementation class. You must also annotate scope
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)
Built-in scope implementations. @author crazybob@google.com (Bob Lee)
Represents a generic type {@code T}. Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.For example, to create a type literal for {@code List
}, you can create an empty anonymous inner class: {@code TypeLiteral
> list = new TypeLiteral
>() {};}
AssumesThisthatsyntax cannot be used to create type literals that have wildcard parameters, such as {@codeTClass<>}implementsorObject{@code List< extends CharSequence>}.equalsSuch type literals must be constructed programatically, either by extracting types from membersandor by using theObjectTypes factory class.Along with modeling generic types, this class can resolve type parameters.
hashCodeFor example, to figure out what type {@code keySet()}asreturns on a {@code Map}, use this code: {@codevalueTypeLiteral(as) {};opposedtoTypeLiteral<> keySetTypeidentity= mapType.getReturnType(Map.class.getMethod("keySet"));comparisonSystem.out.println(keySetType); // prints "Set"} @author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson)