Generated by
JDiff

com.google.inject Documentation Differences

This file contains all the changes in documentation in the package com.google.inject as colored differences. Deletions are shown like 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.

Class AbstractModule

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:
 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);
   }
 }
 
@author crazybob@google.com (Bob Lee)

Class Binder

Collects configuration information (primarily bindings) which will be used to create an Injector. Guice provides this object to your application's Modules implementors 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 contributedsimply 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 {@code Modulebinder}s, definejust howas 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's resolves dependenciesdefault behavior. A You may still want to use this if you prefer your KeyModule consistingclass ofto serve as an explicit manifest for the services it provides. Also, in rare cases, Guice may be unable to validate a type and optionalbinding at injector annotationcreation time unless it is given explicitly.
     bind(Service.class).to(ServiceImpl.class);
Specifies that
uniquelya request for a {@code Service} instance with no identifiesbinding 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
binding withinspecifies that Guice should resolve an unannotated injection request for {@code code InjectorService} 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.

YouThe mayProvider bind fromyou use ahere does not keyhave to: be Anothera binding"factory"; that is, a provider which always creates each instance it provides. However, this bindingis generally a good practice to follow. You can then use Guice's key isconcept of nowscopes to guide when creation should happen -- "aliasedletting toGuice work for you".


 Another    bind(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 referenceswill serve as a Provider"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 this key type. ANote preconstructed instance that it Ais preconstructedstill possible to bind another instance whichof should{@code beServiceImpl} 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.

Besides 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 for this binding use here as well. In


 addition,    bind(new TypeLiteral<PaymentService<CreditCard>>() {})
         .to(CreditCardPaymentService.class);
This admittedly odd construct is the way to bind
a bindingparameterized maytype. haveIt tells Guice how to honor an associatedinjection scoperequest for an element of type {@code PaymentService}. The class {@code CreditCardPaymentService} must implement the {@code PaymentService} interface. Guice cannot currently bind or inject a generic type, such as as Scopes{@code Set}; all type parameters must be fully specified.SINGLETON
     bind(Service.class).toInstance(new ServiceImpl());
     // or, alternatively
     bind(Service.class).toInstance(SomeLegacyRegistry.getService());
In this example, your module itself, not Guice, takes responsibility for obtaining a {@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 and singleton bindingsmethod injection mayfor this instance, but any injectable constructor on {@code ServiceImpl} is simply ignored. specify Note that using this approach results in "eager orloading" behavior that you lazy can't initializationcontrol. See

 the    bindConstant().annotatedWith(ServerHost.class).to(args[0]);
Sets up a constant binding. Constant injections must always be annotated. When a constant usersbinding's guidevalue is a string, it is eligile for conversion to all primitive types, to appendixall 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 the Injector resolves injection annotation is a requestsbit 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
better 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 binding resolutionannotation 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. After

 an    Constructor loneCtor = getLoneCtorFromServiceImplViaReflection();
     bind(ServiceImpl.class)
         .toConstructor(loneCtor);
In this example, we directly tell Guice which constructor to use in a concrete class implementation. It means that we do not need to place {@code Injectorliteral @}Inject has beenon any created,of its bindings maythe constructors and be that Guice treats the provided constructor as though it were annotated so. It is useful for cases where you cannot modify existing classes and is a bit examinedsimpler than using a Provider.

The above list of examples is far from exhaustive. If you can think of how the concepts of one example might coexist with the concepts from another, you can most likely weave the two together. If the two concepts make no sense with each other, you most likely won't be able to do it. In a few cases Guice will let something bogus slip by, and will then inform you of the problems at runtime, as soon as you try to create your Injector.

The other methods likeof Binder such as Injector.getBinding(Key)bindScope, but.bindInterceptor, this .install, read-only.requestStaticInjection, Binding.addError typeand is.currentStage are not used whenpart of creatingthe the Binding bindingsEDSL; 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, AnnotatedBindingBuilder<T> bind(Class<T>)

Creates a binding to aSee the EDSL examples at typeBinder.
Class Binder, LinkedBindingBuilder<T> bind(Key<T>)

Creates a binding to aSee the EDSL examples at keyBinder.
Class Binder, AnnotatedBindingBuilder<T> bind(TypeLiteral<T>)

Creates a binding to aSee the EDSL examples at typeBinder.
Class Binder, AnnotatedConstantBindingBuilder bindConstant()

Binds a constant value toSee the EDSL examples at an annotationBinder.
Class Binder, void bindInterceptor(Matcher<Class<?>>, Matcher<Method>, MethodInterceptor[])

Binds a method interceptor[s] to methods matched by class and method method 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

Class Binding

A mapping from a key (type and optional annotation) to athe providerstrategy for of getting instances of thatthe type. This interface is part of the Injector introspection API and is intended primaryprimarily for use by tools.

Bindings are created in several ways:

They exist on both modules and on injectors, and their behaviour is different for each:

@param the bound type. The injected is always assignable to this type
. @author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson)
Class Binding, Provider<T> getProvider()

Returns the scoped provider guice uses to fulfill requests for thisthis 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.

Class BindingAnnotation

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)

Class CreationException

Thrown when errors occur while creating a Injector. Includes a list list of encounteredencountered errors. Typically, a clientClients should catch this exception, log log it, and stop execution. @author crazybob@google.com (Bob Lee)
Class CreationException, constructor CreationException(Collection<Message>)

ConstructsCreates a newCreationException exceptioncontaining for{@code the given errorsmessages}.
Class CreationException, Collection<Message> getErrorMessages()

Gets the error messages which resulted inReturns messages for the errors that caused this exception.

Class Guice

The entry point to the Guice framework. Creates Injectors from Modules. For advanced usage, see InjectorBuilder.

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();
       }
     }
 
Class Guice, Injector createInjector(Module[])

Creates an injector for the given set of modules. To create an injector with a Stage or other options, see InjectorBuilder. @throws CreationException from which you can retrieveif one or more errors theoccur during injector individual error messagesconstruction
Class Guice, Injector createInjector(Stage, Module[])

Creates an injector for the given set of modules, in a given development stage. Use InjectorBuilder for advanced injector creation. @throws CreationException from which you can retrieveif one or more errors theoccur during injector individual error messagescreation.

Class Injector

FulfillsBuilds requests for the objectgraphs instancesof objects that make up your application, . always ensuring that these instances are properly injected before they are The injector tracks the dependencies for each type and uses bindings returned.to Theinject {@codethem. Injector}This is the heartcore of the Guice framework, although you don't typicallyrarely interact with it directly very often. This This "behind-the-scenes" operation is what distinguishes the dependency injection pattern from 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.

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, List<Binding<T>> findBindingsByType(TypeLiteral<T>)

FindsReturns all explicit bindings tofor {@code type}.

This method is part of the givenGuice typeSPI and is intended for use by tools and extensions.

Class Injector, Binding<T> getBinding(Key<T>)

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, Map<Key<?>, Binding<?>> getBindings()

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(Class<T>)

Gets an instance bound toReturns the appropriate instance for the given injection type; equivalent to to {@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, T getInstance(Key<T>)

Gets an instance bound toReturns the appropriate instance for the given injection key; equivalent to to {@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(Class<T>)

GetsReturns the provider boundused 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, Provider<T> getProvider(Key<T>)

GetsReturns the provider boundused 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
Class Injector, void injectMembers(Object)

Injects dependencies into the fields and methods of {@code instance}. Ignores the presence or absence of an existing objectinjectable constructor. Does

Whenever not injectGuice creates thean 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


Class Key

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)


Class Module

A module contributes configuration information, typically interface bindings, which will be used to create an Injector. A 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.

Class Module, void configure(Binder)

Contributes bindings and other configurations tofor this amodule to {@code Binderbinder}.

Do not invoke this method directly to install submodules. Instead use Binder.install(Module), which ensures that provider methods are discovered.


Class Provider

Simply, anyAn object capable of providing instances of type {@code T}. Providers are used in numerous waysways by the Guice framework: @param the type of object this provider provides @author crazybob@google.com (Bob Lee)
Class Provider, T get()

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.

Class Scope

A scope is a level of visibility that instances provided by Guice may have. By default, an instance created by the Injector has no no 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 a particular binding particular binding allows the created instance to be "remembered" and possibly usedused again for for other injections. @see

An example of a scope is Scopes#SINGLETON .SINGLETON. @author crazybob@google.com (Bob Lee)

Class Scope, Provider<T> scope(Key<T>, Provider<T>)

Scopes a provider. The returned locatorprovider returns objects from this scope. If If 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


Class ScopeAnnotation

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)

Class Scopes

Built -in scope implementations. @author crazybob@google.com (Bob Lee)

Class TypeLiteral

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>() {};}

AssumesThis thatsyntax cannot be used to create type literals that have wildcard parameters, such as {@code TClass<>} implementsor Object{@code List< extends CharSequence>}.equals Such type literals must be constructed programatically, either by extracting types from members and or by using the ObjectTypes factory class.

Along with modeling generic types, this class can resolve type parameters.hashCode For example, to figure out what type {@code keySet()} asreturns on a {@code Map}, use this code:

   {@code

 value  TypeLiteral> mapType
       = new TypeLiteral>(as) {};
 opposed to TypeLiteral<> keySetType
       identity= mapType.getReturnType(Map.class.getMethod("keySet"));
 comparison  System.out.println(keySetType); // prints "Set"}
@author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson)