|
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.uniquelybind(Service.class).to(ServiceImpl.class);
Specifies that a request for a {@codeidentifiesService} instance with no binding 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'skeyconceptisof scopes to guide whennowcreation 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 binding will servereferencesas aProvider"catch-all" forthis keyany valuesAofpreconstructed{@codeinstance@Red}Athatpreconstructed instance which should be usedhave no exact match in theasbindings.bind(ServiceImpl.class).in(Singleton.class);// or, alternatively bind(ServiceImpl.class).in(Scopes.SINGLETON); Either of these statements places theProvider{@code ServiceImpl} class into singleton scope. Guice will create only one instance of {@code ServiceImpl} and will reuse it for all injection requests of thisbindingtype.InNoteaddition,thatait is still possible to bind another instance of {@code ServiceImpl} if the second bindingmayishavequalified by anassociatedannotationscopeas in the previous example. Guice is not overly concerned with preventing you from creating multiple instances of your "singletons",suchonly 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
asthe {@code ServiceImpl} class.Besides
Singleton/Scopes.SINGLETON, there are servlet-specific scopes available in {@code com.google.inject.servlet.ServletScopes}, andsingleton bindings may specify eageryour Modules can contribute theirorown customlazyscopesinitializationfor use here as well.Seebind(new TypeLiteral<PaymentService<CreditCard>>() {}) .to(CreditCardPaymentService.class);
This admittedly odd construct is theusers'wayguideto bind a parameterized type. It tells Guice how to honor an injection request for an element of type {@code PaymentService}. The class {@code CreditCardPaymentService} must implement the {@code appendixPaymentService} interface. Guice cannot currently bind or inject a generic type ,"HowsuchtheasInjector{@code Set}; resolves injectionall typerequestsparameters must be fully specified.bind(Service.class).toInstance(new ServiceImpl()); // or,"toalternativelybetterunderstandbindingresolutionbind(Service.class).toInstance(SomeLegacyRegistry.getService());AfterInanthis example, your module itself, not Guice, takes responsibility for obtaining a {@codeInjectorServiceImpl}hasinstance, then asks Guice to always use this single instancebeento fulfill all {@code Service} injection requests. When the Injector is created,its bindings mayit will automaticallybeperform field and method injection for this instance, but any injectable constructor on {@code ServiceImpl} is simply ignored.examinedNote that usingmethodsthis 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 eligile for conversion to alllikeprimitive types, toInjectorall enums, and to class literals.getBindingConversions for other types can be configured using convertToTypes(Key).{@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 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,butshown above, is to apply a prototype annotation to a field in yourthismodule class, so that you can read-onlythis 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,Binding@Named.typeBecause of Guice's library support, binding by name isnot used whenquite easier thancreatingin thebindingsarbitrary 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, .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. @author crazybob@google
.com (Bob Lee)
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.
Binds a constant value toSee the EDSL examples atan annotationBinder.
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(Iterable<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.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. @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. @throws CreationExceptionfrom which you can retrieve the individual errorif one or more errors occur during Injectormessages.creation
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 and methods 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)
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>)GetsReturns all explicit 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.
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.
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.
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.
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
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
>() {};}
Assumes that type {@code T} implements Object.equals and Object.hashCode() as value (as opposed to identity) comparison. @author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson)