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)]]>
  • 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
  • @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. The interceptors are called in the order they are given.]]>
    bind(Foo.class).to(FooImpl.class)) are allowed, but the implicit binding (FooImpl) cannot be directly injected unless it is also explicitly bound (bind(FooImpl.class)).

    Tools can still retrieve bindings for implicit bindings (bindings created through a linked binding) if explicit bindings are required, however {@link Binding#getProvider} will fail.

    By default, explicit bindings are not required.

    If a parent injector requires explicit bindings, then all child injectors (and private modules within that injector) also require explicit bindings. If a parent does not require explicit bindings, a child injector or private module may optionally declare itself as requiring explicit bindings. If it does, the behavior is limited only to that child or any grandchildren. No siblings of the child will require explicit bindings.

    If the parent did not require explicit bindings but the child does, it is possible that a linked binding in the child may add a JIT binding to the parent. The child will not be allowed to reference the target binding directly, but the parent and other children of the parent may be able to. @since 3.0]]> If a parent injector disables circular proxies, then all child injectors (and private modules within that injector) also disable circular proxies. If a parent does not disable circular proxies, a child injector or private module may optionally declare itself as disabling circular proxies. If it does, the behavior is limited only to that child or any grandchildren. No siblings of the child will disable circular proxies. @since 3.0]]> If the class is bound using {@link LinkedBindingBuilder#toConstructor}, Guice will still inject that constructor regardless of annotations. @since 4.0]]> {@literal @}Named Foo when attempting to inject {@literal @}Named("foo") Foo. @since 4.0]]> bindings) which will be used to create an {@link Injector}. Guice provides this object to your application's {@link Module} 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 simply and readably. This approach is great for overall usability, but it does come with a small cost: it is difficult to learn how to use the Binding EDSL by reading method-level javadocs. Instead, you should consult the series of examples below. To save space, these examples omit the opening {@code binder}, just as you will if your module extends {@link AbstractModule}.
         bind(ServiceImpl.class);
    This statement does essentially nothing; it "binds the {@code ServiceImpl} class to itself" and does not change Guice's default behavior. You may still want to use this if you prefer your {@link Module} class to serve as an explicit manifest for the services it provides. Also, in rare cases, Guice may be unable to validate a binding at injector creation time unless it is given explicitly.
         bind(Service.class).to(ServiceImpl.class);
    Specifies that a request for a {@code Service} 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 {@link ImplementedBy @ImplementedBy} or {@link ProvidedBy @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 specifies that Guice should resolve an unannotated injection request for {@code Service} by first resolving an instance of {@code ServiceProvider} in the regular way, then calling {@link Provider#get get()} on the resulting Provider instance to obtain the {@code Service} instance.

    The {@link Provider} you use here does not have to be a "factory"; that is, a provider which always creates each instance it provides. However, this is generally a good practice to follow. You can then use Guice's concept of {@link Scope scopes} to guide when creation should happen -- "letting Guice work for you".

         bind(Service.class).annotatedWith(Red.class).to(ServiceImpl.class);
    Like the previous example, but only applies to injection requests that use the binding annotation {@code @Red}. If your module also includes bindings for particular values of the {@code @Red} annotation (see below), then this binding will serve as a "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 type. Note that it is still possible to bind another instance of {@code ServiceImpl} if 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 {@link Singleton}/{@link 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 use here as well.

         bind(new TypeLiteral<PaymentService<CreditCard>>() {})
             .to(CreditCardPaymentService.class);
    This admittedly odd construct is the way to bind a parameterized type. It tells Guice how to honor an injection request for an element of type {@code PaymentService}. The class {@code CreditCardPaymentService} must implement the {@code PaymentService} interface. Guice cannot currently bind or inject a generic type, such as {@code Set}; all type parameters must be fully specified.
         bind(Service.class).toInstance(new ServiceImpl());
         // or, alternatively
         bind(Service.class).toInstance(SomeLegacyRegistry.getService());
    In this example, your module itself, not Guice, takes responsibility for obtaining a {@code ServiceImpl} instance, then asks Guice to always use this single instance to fulfill all {@code Service} injection requests. When the {@link Injector} is created, it will automatically perform field and method injection for this instance, but any injectable constructor on {@code ServiceImpl} is simply ignored. Note that using this approach results in "eager loading" behavior that you can't control.
         bindConstant().annotatedWith(ServerHost.class).to(args[0]);
    Sets up a constant binding. Constant injections must always be annotated. When a constant binding's value is a string, it is eligile for conversion to all primitive types, to {@link Enum#valueOf(Class, String) all enums}, and to {@link Class#forName class literals}. Conversions for other types can be configured using {@link #convertToTypes(Matcher, TypeConverter) 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 bindings to different specific values of your annotation. Getting your hands on the right instance of the annotation is a bit of a pain -- one approach, shown above, is to apply a prototype annotation to a field in your module class, so that you can read this annotation instance and give it to Guice.
         bind(Service.class)
             .annotatedWith(Names.named("blue"))
             .to(BlueService.class);
    Differentiating by names is a common enough use case that we provided a standard annotation, {@link com.google.inject.name.Named @Named}. Because of Guice's library support, binding by name is quite easier than in the arbitrary binding annotation case we just saw. However, remember that these names will live in a single flat namespace with all the other names used in your application.
         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 {@literal @}Inject on any of the constructors and 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 simpler than using a {@link 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 of Binder such as {@link #bindScope}, {@link #bindInterceptor}, {@link #install}, {@link #requestStaticInjection}, {@link #addError} and {@link #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) @author jessewilson@google.com (Jesse Wilson) @author kevinb@google.com (Kevin Bourrillion)]]> 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 {@link ImplementedBy pointer} {@link ProvidedBy annotations} or by using its {@link Inject annotated} or default constructor.
    • By converting a bound instance to a different type.
    • For {@link Provider 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:

    • 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 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 the bound type. The injected is always assignable to this type. @author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson)]]>
    {@code @}Retention(RUNTIME) {@code @}Target({ FIELD, PARAMETER, METHOD }) {@code @}BindingAnnotation public {@code @}interface Transactional {} @author crazybob@google.com (Bob Lee)]]> 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();
           }
         }
     
    ]]>
  • Every instance it constructs. The class being constructed must have exactly one of its constructors marked with {@code @Inject} or must have a constructor taking no parameters. The Injector then proceeds to perform field and method injections.
  • Pre-constructed instances passed to {@link Injector#injectMembers}, {@link com.google.inject.binder.LinkedBindingBuilder#toInstance(Object)} and {@link com.google.inject.binder.LinkedBindingBuilder#toProvider(javax.inject.Provider)}. In this case all constructors are, of course, ignored.
  • Static fields and methods of classes which any {@link Module} has specifically requested static injection for, using {@link Binder#requestStaticInjection}. In all cases, a member can be injected regardless of its Java access specifier (private, default, protected, public). @author crazybob@google.com (Bob Lee)]]> 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 on @see Binder#getMembersInjector(Class) for a preferred alternative that supports checks before run time]]> explicit bindings.

    The returned map does not include bindings inherited from a {@link #getParent() parent injector}, should one exist. The returned map is guaranteed to iterate (for example, with its {@link 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.]]> both explicit and just-in-time. The returned map is immutable; it contains only the bindings that were present when {@code getAllBindings()} was invoked. Subsequent calls may return a map with additional just-in-time bindings.

    The returned map does not include bindings inherited from a {@link #getParent() 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]]> 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.]]> 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. @since 2.0]]> This method is part of the Guice SPI and is intended for use by tools and extensions. @since 3.0]]> This method is part of the Guice SPI and is intended for use by tools and extensions.]]> 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 be silently ignored if 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]]> 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.

    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]]> This method is part of the Guice SPI and is intended for use by tools and extensions. @since 3.0]]> This method is part of the Guice SPI and is intended for use by tools and extensions. @since 3.0]]> Contains several default bindings:

    • This {@link Injector} instance itself
    • A {@code Provider} for each binding of type {@code T}
    • The {@link java.util.logging.Logger} for the class being injected
    • The {@link Stage} in which the Injector was created
    Injectors are created using the facade class {@link Guice}.

    An injector can also {@link #injectMembers(Object) inject the dependencies} of already-constructed instances. This can be used to interoperate with objects created by other frameworks or services.

    Injectors can be {@link #createChildInjector(Iterable) hierarchical}. Child injectors inherit the configuration of their parent injectors, but the converse does not hold.

    The injector's {@link #getBindings() 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)]]> Clients create an empty anonymous subclass. Doing so embeds the type parameter in the anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.

    Example usage for a binding of type {@code Foo} annotated with {@code @Bar}:

    {@code new Key(Bar.class) {}}.]]> Clients create an empty anonymous subclass. Doing so embeds the type parameter in the anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.

    Example usage for a binding of type {@code Foo} annotated with {@code @Bar}:

    {@code new Key(new Bar()) {}}.]]> Clients create an empty anonymous subclass. Doing so embeds the type parameter in the anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.

    Example usage for a binding of type {@code Foo}:

    {@code new Key() {}}.]]> 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 {@link 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)]]> 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 on. May be {@code null}.]]> type to inject members of @author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson) @since 2.0]]> Do not invoke this method directly to install submodules. Instead use {@link Binder#install(Module)}, which ensures that {@link Provides provider methods} are discovered.]]> Your Module classes can use a more streamlined syntax by extending {@link AbstractModule} rather than implementing this interface directly.

    In addition to the bindings configured via {@link #configure}, bindings will be created for all methods annotated with {@literal @}{@link Provides}. Use scope and binding annotations on these methods to configure the bindings.]]> A private module can be nested within a regular module or within another private module using {@link Binder#install 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 {@link #expose(Class) expose()}. {@literal @}{@link com.google.inject.Provides Provides} bindings can be exposed with the {@literal @}{@link 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 {@link Injector#createChildInjector(Module[]) 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]]>
  • 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 {@link 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 {@link Injector} offers access to the {@code Provider} it uses to fulfill requests for a given key, via the {@link Injector#getProvider} methods. @param the type of object this provides @author crazybob@google.com (Bob Lee)]]> Scope implementations are strongly encouraged to override {@link 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]]> 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 allows the created instance to be "remembered" and possibly used again for other injections.

    An example of a scope is {@link Scopes#SINGLETON}. @author crazybob@google.com (Bob Lee)]]> {@code @}Retention(RUNTIME) {@code @}Target(TYPE, METHOD) {@code @}ScopeAnnotation public {@code @}interface SessionScoped {} @author crazybob@google.com (Bob Lee)]]> not cache 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 lead to IllegalArgumentExceptions or ClassCastExceptions.)]]> This exists only in case a class has been annotated with a scope annotation such as {@link Singleton @Singleton}, and you need to override this to "no scope" in your binding. @since 2.0]]> Clients create an empty anonymous subclass. Doing so embeds the type parameter in the anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.]]> }, this returns {@code Iterable} given the input {@code Iterable.class}. @param supertype a superclass of, or interface implemented by, this. @since 2.0]]> For example, to create a type literal for {@code List}, you can create an empty anonymous inner class:

    {@code TypeLiteral> list = new TypeLiteral>() {};}

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

       {@code
    
       TypeLiteral> mapType
           = new TypeLiteral>() {};
       TypeLiteral keySetType
           = mapType.getReturnType(Map.class.getMethod("keySet"));
       System.out.println(keySetType); // prints "Set"}
    @author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson)]]>
    When used in tandem with {@link FactoryModuleBuilder}, constructors annotated with {@code @AssistedInject} indicate that multiple constructors can be injected, each with different parameters. AssistedInject annotations should not be mixed with {@literal @}{@link Inject} annotations. The assisted parameters must exactly match one corresponding factory method within the factory interface, but the parameters do not need to be in the same order. Constructors annotated with AssistedInject are created by Guice and receive all the benefits (such as AOP).

    Obsolete Usage: When used in tandem with {@link FactoryProvider}, constructors annotated with {@code @AssistedInject} trigger a "backwards compatibility mode". The assisted parameters must exactly match one corresponding factory method within the factory interface and all must be in the same order as listed in the factory. In this backwards compatable mode, constructors annotated with AssistedInject are not created by Guice and thus receive none of the benefits.

    Constructor parameters must be either supplied by the factory interface and marked with @Assisted, or they must be injectable. @author jmourits@google.com (Jerome Mourits) @author jessewilson@google.com (Jesse Wilson)]]> The fully qualified type of the factory. @since 3.0 @author ramakrishna@google.com (Ramakrishna Rajanna)]]> If your {@link BindingTargetVisitor} implements this interface, bindings created by using {@link FactoryModuleBuilder} will be visited through this interface. @since 3.0 @author ramakrishna@google.com (Ramakrishna Rajanna)]]> Defining a factory Create an interface whose methods return the constructed type, or any of its supertypes. The method's parameters are the arguments required to build the constructed type.

    public interface PaymentFactory {
       Payment create(Date startDate, Money amount);
     }
    You can name your factory methods whatever you like, such as create, createPayment or newPayment.

    Creating a type that accepts factory parameters

    {@code constructedType} is a concrete class with an {@literal @}{@link com.google.inject.Inject Inject}-annotated constructor. In addition to injector-supplied parameters, the constructor should have parameters that match each of the factory method's parameters. Each factory-supplied parameter requires an {@literal @}{@link Assisted} annotation. This serves to document that the parameter is not bound by your application's modules.
    public class RealPayment implements Payment {
       {@literal @}Inject
       public RealPayment(
          CreditService creditService,
          AuthService authService,
          {@literal @}Assisted Date startDate,
          {@literal @}Assisted Money amount) {
         ...
       }
     }

    Multiple factory methods for the same type

    If the factory contains many methods that return the same type, you can create multiple constructors in your concrete class, each constructor marked with with {@literal @}{@link AssistedInject}, in order to match the different parameters types of the factory methods.
    public interface PaymentFactory {
        Payment create(Date startDate, Money amount);
        Payment createWithoutDate(Money amount);
     }
     
     public class RealPayment implements Payment {
      {@literal @}AssistedInject
       public RealPayment(
          CreditService creditService,
          AuthService authService,
         {@literal @}Assisted Date startDate,
         {@literal @}Assisted Money amount) {
         ...
       }
       
      {@literal @}AssistedInject
       public RealPayment(
          CreditService creditService,
          AuthService authService,
         {@literal @}Assisted Money amount) {
         ...
       }   
     }

    Configuring simple factories

    In your {@link Module module}, install a {@code FactoryModuleBuilder} that creates the factory:
    install(new FactoryModuleBuilder()
         .implement(Payment.class, RealPayment.class)
         .build(PaymentFactory.class);
    As a side-effect of this binding, Guice will inject the factory to initialize it for use. The factory cannot be used until the injector has been initialized.

    Configuring complex factories

    Factories can create an arbitrary number of objects, one per each method. Each factory method can be configured using .implement.
    public interface OrderFactory {
        Payment create(Date startDate, Money amount);
        Shipment create(Customer customer, Item item);
        Receipt create(Payment payment, Shipment shipment);
     }
     
     [...]
     
     install(new FactoryModuleBuilder()
         .implement(Payment.class, RealPayment.class)
         // excluding .implement for Shipment means the implementation class
         // will be 'Shipment' itself, which is legal if it's not an interface.
         .implement(Receipt.class, RealReceipt.class)
         .build(OrderFactory.class);

    Using the factory

    Inject your factory into your application classes. When you use the factory, your arguments will be combined with values from the injector to construct an instance.
    public class PaymentAction {
       {@literal @}Inject private PaymentFactory paymentFactory;
    
       public void doPayment(Money amount) {
         Payment payment = paymentFactory.create(new Date(), amount);
         payment.apply();
       }
     }

    Making parameter types distinct

    The types of the factory method's parameters must be distinct. To use multiple parameters of the same type, use a named {@literal @}{@link Assisted} annotation to disambiguate the parameters. The names must be applied to the factory method's parameters:
    public interface PaymentFactory {
       Payment create(
           {@literal @}Assisted("startDate") Date startDate,
           {@literal @}Assisted("dueDate") Date dueDate,
           Money amount);
     } 
    ...and to the concrete type's constructor parameters:
    public class RealPayment implements Payment {
       {@literal @}Inject
       public RealPayment(
          CreditService creditService,
          AuthService authService,
          {@literal @}Assisted("startDate") Date startDate,
          {@literal @}Assisted("dueDate") Date dueDate,
          {@literal @}Assisted Money amount) {
         ...
       }
     }

    Values are created by Guice

    Returned factories use child injectors to create values. The values are eligible for method interception. In addition, {@literal @}{@literal Inject} members will be injected before they are returned.

    More configuration options

    In addition to simply specifying an implementation class for any returned type, factories' return values can be automatic or can be configured to use annotations:

    If you just want to return the types specified in the factory, do not configure any implementations:

    public interface FruitFactory {
       Apple getApple(Color color);
     }
     ...
     protected void configure() {
       install(new FactoryModuleBuilder().build(FruitFactory.class));
     }
    Note that any type returned by the factory in this manner needs to be an implementation class.

    To return two different implementations for the same interface from your factory, use binding annotations on your return types:

    interface CarFactory {
       {@literal @}Named("fast") Car getFastCar(Color color);
       {@literal @}Named("clean") Car getCleanCar(Color color);
     }
     ...
     protected void configure() {
       install(new FactoryModuleBuilder()
           .implement(Car.class, Names.named("fast"), Porsche.class)
           .implement(Car.class, Names.named("clean"), Prius.class)
           .build(CarFactory.class));
     }

    Implementation limitations

    As a limitation of the implementation, it is prohibited to declare a factory method that accepts a {@code Provider} as one of its arguments. @since 3.0 @author schmitt@google.com (Peter Schmitt)]]>
    Obsolete. Prefer {@link FactoryModuleBuilder} for its more concise API and additional capability.

    Provides a factory that combines the caller's arguments with injector-supplied values to construct objects.

    Defining a factory

    Create an interface whose methods return the constructed type, or any of its supertypes. The method's parameters are the arguments required to build the constructed type.
    public interface PaymentFactory {
       Payment create(Date startDate, Money amount);
     }
    You can name your factory methods whatever you like, such as create, createPayment or newPayment.

    Creating a type that accepts factory parameters

    {@code constructedType} is a concrete class with an {@literal @}{@link Inject}-annotated constructor. In addition to injector-supplied parameters, the constructor should have parameters that match each of the factory method's parameters. Each factory-supplied parameter requires an {@literal @}{@link Assisted} annotation. This serves to document that the parameter is not bound by your application's modules.
    public class RealPayment implements Payment {
       {@literal @}Inject
       public RealPayment(
          CreditService creditService,
          AuthService authService,
          {@literal @}Assisted Date startDate,
          {@literal @}Assisted Money amount) {
         ...
       }
     }
    Any parameter that permits a null value should also be annotated {@code @Nullable}.

    Configuring factories

    In your {@link com.google.inject.Module module}, bind the factory interface to the returned factory:
    bind(PaymentFactory.class).toProvider(
         FactoryProvider.newFactory(PaymentFactory.class, RealPayment.class));
    As a side-effect of this binding, Guice will inject the factory to initialize it for use. The factory cannot be used until the injector has been initialized.

    Using the factory

    Inject your factory into your application classes. When you use the factory, your arguments will be combined with values from the injector to construct an instance.
    public class PaymentAction {
       {@literal @}Inject private PaymentFactory paymentFactory;
    
       public void doPayment(Money amount) {
         Payment payment = paymentFactory.create(new Date(), amount);
         payment.apply();
       }
     }

    Making parameter types distinct

    The types of the factory method's parameters must be distinct. To use multiple parameters of the same type, use a named {@literal @}{@link Assisted} annotation to disambiguate the parameters. The names must be applied to the factory method's parameters:
    public interface PaymentFactory {
       Payment create(
           {@literal @}Assisted("startDate") Date startDate,
           {@literal @}Assisted("dueDate") Date dueDate,
           Money amount);
     } 
    ...and to the concrete type's constructor parameters:
    public class RealPayment implements Payment {
       {@literal @}Inject
       public RealPayment(
          CreditService creditService,
          AuthService authService,
          {@literal @}Assisted("startDate") Date startDate,
          {@literal @}Assisted("dueDate") Date dueDate,
          {@literal @}Assisted Money amount) {
         ...
       }
     }

    Values are created by Guice

    Returned factories use child injectors to create values. The values are eligible for method interception. In addition, {@literal @}{@literal Inject} members will be injected before they are returned.

    Backwards compatibility using {@literal @}AssistedInject

    Instead of the {@literal @}Inject annotation, you may annotate the constructed classes with {@literal @}{@link AssistedInject}. This triggers a limited backwards-compatability mode.

    Instead of matching factory method arguments to constructor parameters using their names, the parameters are matched by their order. The first factory method argument is used for the first {@literal @}Assisted constructor parameter, etc.. Annotation names have no effect.

    Returned values are not created by Guice. These types are not eligible for method interception. They do receive post-construction member injection. @param The factory interface @author jmourits@google.com (Jerome Mourits) @author jessewilson@google.com (Jesse Wilson) @author dtm@google.com (Daniel Martin) @deprecated use {@link FactoryModuleBuilder} instead.]]> } and an instance node with the same {@link Key} and value of 42. @author bojand@google.com (Bojan Djordjevic)]]> See: http://www.graphviz.org/doc/info/arrows.html @author phopkins@gmail.com (Pete Hopkins)]]> See: http://www.graphviz.org/doc/info/attrs.html#k:portPos @author phopkins@gmail.com (Pete Hopkins)]]> See: http://www.graphviz.org/doc/info/attrs.html#k:style @author phopkins@gmail.com (Pete Hopkins)]]> Specify the {@link PrintWriter} to output to with {@link #setOut(PrintWriter)}. @author phopkins@gmail.com (Pete Hopkins)]]> See: http://www.graphviz.org/doc/info/shapes.html @author phopkins@gmail.com (Pete Hopkins)]]> See: http://www.graphviz.org/doc/info/attrs.html#k:style @author phopkins@gmail.com (Pete Hopkins)]]> bind(DataSource.class).toProvider(fromJndi(DataSource.class, "java:...")); ]]> When multiple equal keys are bound, the value that gets included in the map is arbitrary.

    In addition to the {@code Map} and {@code Map>} maps that are normally bound, a {@code Map>} and {@code Map>>} are also bound, which contain all values bound to each key.

    When multiple modules contribute elements to the map, this configuration option impacts all of them. @return this map binder @since 3.0]]> It is an error to call this method without also calling one of the {@code to} methods on the returned binding builder.

    Scoping elements independently is supported. Use the {@code in} method to specify a binding scope.]]> public class SnacksModule extends AbstractModule { protected void configure() { MapBinder<String, Snack> mapbinder = MapBinder.newMapBinder(binder(), String.class, Snack.class); mapbinder.addBinding("twix").toInstance(new Twix()); mapbinder.addBinding("snickers").toProvider(SnickersProvider.class); mapbinder.addBinding("skittles").to(Skittles.class); } }

    With this binding, a {@link Map}{@code } can now be injected:

    
     class SnackMachine {
       {@literal @}Inject
       public SnackMachine(Map<String, Snack> snacks) { ... }
     }

    In addition to binding {@code Map}, a mapbinder will also bind {@code Map>} for lazy value provision:

    
     class SnackMachine {
       {@literal @}Inject
       public SnackMachine(Map<String, Provider<Snack>> snackProviders) { ... }
     }

    Contributing mapbindings from different modules is supported. For example, it is okay to have both {@code CandyModule} and {@code ChipsModule} both create their own {@code MapBinder}, and to each contribute bindings to the snacks map. When that map is injected, it will contain entries from both modules.

    The map's iteration order is consistent with the binding order. This is convenient when multiple elements are contributed by the same module because that module can order its bindings appropriately. Avoid relying on the iteration order of elements contributed by different modules, since there is no equivalent mechanism to order modules.

    The map is unmodifiable. Elements can only be added to the map by configuring the MapBinder. Elements can never be removed from the map.

    Values are resolved at map injection time. If a value is bound to a provider, that provider's get method will be called each time the map is injected (unless the binding is also scoped, or a map of providers is injected).

    Annotations are used to create different maps of the same key/value type. Each distinct annotation gets its own independent map.

    Keys must be distinct. If the same key is bound more than once, map injection will fail. However, use {@link #permitDuplicates()} in order to allow duplicate keys; extra bindings to {@code Map>} and {@code Map>} will be added.

    Keys must be non-null. {@code addBinding(null)} will throw an unchecked exception.

    Values must be non-null to use map injection. If any value is null, map injection will fail (although injecting a map of providers will not). @author dpb@google.com (David P. Baker)]]> The TypeLiteral will always match the type Map's generic type. For example, if getMapKey returns a key of Map<String, Snack>, then this will always return a TypeLiteral<String>.]]> The TypeLiteral will always match the type Map's generic type. For example, if getMapKey returns a key of Map<String, Snack>, then this will always return a TypeLiteral<Snack>.]]> The elements will always match the type Map's generic type. For example, if getMapKey returns a key of Map<String, Snack>, then this will always return a list of type List<Map.Entry<String, Binding<Snack>>>.]]> If you need to introspect the details of the map, such as the keys, values or if it permits duplicates, it is necessary to pass the elements through an Injector and use {@link #getEntries()} and {@link #permitsDuplicates()}.]]> Although MapBinders may be injected through a variety of generic types (Map<K, V>, Map <K, Provider<V>>, Map<K, Set<V>>, Map>, and even Set<Map.Entry<K, Provider<V>>), a MapBinderBinding exists only on the Binding associated with the Map<K, V> key. Other bindings can be validated to be derived from this MapBinderBinding using {@link #containsElement(Element)}. @param The fully qualified type of the map, including Map. For example: MapBinderBinding<Map<String, Snack>> @since 3.0 @author sameb@google.com (Sam Berlin)]]> It is an error to call this method without also calling one of the {@code to} methods on the returned binding builder.

    Scoping elements independently is supported. Use the {@code in} method to specify a binding scope.]]> public class SnacksModule extends AbstractModule { protected void configure() { Multibinder<Snack> multibinder = Multibinder.newSetBinder(binder(), Snack.class); multibinder.addBinding().toInstance(new Twix()); multibinder.addBinding().toProvider(SnickersProvider.class); multibinder.addBinding().to(Skittles.class); } }

    With this binding, a {@link Set}{@code } can now be injected:

    
     class SnackMachine {
       {@literal @}Inject
       public SnackMachine(Set<Snack> snacks) { ... }
     }

    Contributing multibindings from different modules is supported. For example, it is okay for both {@code CandyModule} and {@code ChipsModule} to create their own {@code Multibinder}, and to each contribute bindings to the set of snacks. When that set is injected, it will contain elements from both modules.

    The set's iteration order is consistent with the binding order. This is convenient when multiple elements are contributed by the same module because that module can order its bindings appropriately. Avoid relying on the iteration order of elements contributed by different modules, since there is no equivalent mechanism to order modules.

    The set is unmodifiable. Elements can only be added to the set by configuring the multibinder. Elements can never be removed from the set.

    Elements are resolved at set injection time. If an element is bound to a provider, that provider's get method will be called each time the set is injected (unless the binding is also scoped).

    Annotations are be used to create different sets of the same element type. Each distinct annotation gets its own independent collection of elements.

    Elements must be distinct. If multiple bound elements have the same value, set injection will fail.

    Elements must be non-null. If any set element is null, set injection will fail. @author jessewilson@google.com (Jesse Wilson)]]> The elements will always match the type Set's generic type. For example, if getSetKey returns a key of Set<String>, then this will always return a TypeLiteral<String>.]]> The elements will always match the type Set's generic type. For example, if getSetKey returns a key of Set<String>, then this will always return a list of type List<Binding<String>>.]]> If you need to introspect the details of the set, such as the values or if it permits duplicates, it is necessary to pass the elements through an Injector and use {@link #getElements()} and {@link #permitsDuplicates()}.]]> The fully qualified type of the set, including Set. For example: MultibinderBinding<Set<Boolean>> @since 3.0 @author sameb@google.com (Sam Berlin)]]> If your {@link BindingTargetVisitor} implements this interface, bindings created by using {@link Multibinder} or {@link MapBinder} will be visited through this interface. @since 3.0 @author sameb@google.com (Sam Berlin)]]> To be able to use the open session-in-view pattern (i.e. work per request), register this filter once in your Guice {@code ServletModule}. It is important that you register this filter before any other filter. For multiple providers, you should register this filter once per provider, inside a private module for each persist module installed (this must be the same private module where the specific persist module is itself installed).

    Example configuration:

    {@code
      public class MyModule extends ServletModule {
        public void configureServlets() {
          filter("/*").through(PersistFilter.class);
    
          serve("/index.html").with(MyHtmlServlet.class);
          // Etc.
        }
      }
     }

    This filter is thread safe and allows you to create injectors concurrently and deploy multiple guice-persist modules within the same injector, or even multiple injectors with persist modules withing the same JVM or web app.

    This filter requires the Guice Servlet extension. @author Dhanji R. Prasanna (dhanji@gmail.com)]]> Any method or class marked with this annotation will be considered for transactionality. Consult the documentation on http://code.google.com/p/google-guice for detailed semantics. Marking a method {@code @Transactional} will start a new transaction before the method executes and commit it after the method returns.

    If the method throws an exception, the transaction will be rolled back unless you have specifically requested not to in the {@link #ignore()} clause.

    Similarly, the set of exceptions that will trigger a rollback can be defined in the {@link #rollbackOn()} clause. By default, only unchecked exceptions trigger a rollback. @author Dhanji R. Prasanna (dhanji@gmail.com)]]> Transaction semantics are not affected.]]> The Unit of Work referred to by UnitOfWork will always be local to the calling thread. Be careful to end() in a finally block. Neither JPA, nor Hibernate supports threadsafe sessions (reasoning behind thread-locality of Unit of Work semantics).

    • Using UnitOfWork with the PersistFilter inside a request is not recommended.
    • Using UnitOfWork with session-per-txn strategy is not terribly clever either.
    • Using UnitOfWork with session-per-request strategy but *outside* a request (i.e. in a background or bootstrap thread) is probably a good use case.
    @author Dhanji R. Prasanna (dhanji@gmail com)]]>
    Apply this filter in web.xml above all other filters (typically), to all requests where you plan to use servlet scopes. This is also needed in order to dispatch requests to injectable filters and servlets:
      <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
      </filter>
    
      <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
      
    This filter must appear before every filter that makes use of Guice injection or servlet scopes functionality. Typically, you will only register this filter in web.xml and register any other filters (and servlets) using a {@link ServletModule}. @author crazybob@google.com (Bob Lee) @author dhanji@gmail.com (Dhanji R. Prasanna)]]>
    } when you want the HTTP request parameter map to be injected. @author crazybob@google.com (Bob Lee)]]> Servlet Mapping EDSL

    Part of the EDSL builder language for configuring servlets and filters with guice-servlet. Think of this as an in-code replacement for web.xml. Filters and servlets are configured here using simple java method calls. Here is a typical example of registering a filter when creating your Guice injector:

       Guice.createInjector(..., new ServletModule() {
    
         {@literal @}Override
         protected void configureServlets() {
           serve("*.html").with(MyServlet.class)
         }
       }
     
    This registers a servlet (subclass of {@code HttpServlet}) called {@code MyServlet} to service any web pages ending in {@code .html}. You can also use a path-style syntax to register servlets:
           serve("/my/*").with(MyServlet.class)
     
    Every servlet (or filter) is required to be a singleton. If you cannot annotate the class directly, you should add a separate {@code bind(..).in(Singleton.class)} rule elsewhere in your module. Mapping a servlet that is bound under any other scope is an error.

    Dispatch Order

    You are free to register as many servlets and filters as you like this way. They will be compared and dispatched in the order in which the filter methods are called:
    
       Guice.createInjector(..., new ServletModule() {
    
         {@literal @}Override
         protected void configureServlets() {
           filter("/*").through(MyFilter.class);
           filter("*.css").through(MyCssFilter.class);
           filter("*.jpg").through(new MyJpgFilter());
           // etc..
    
           serve("*.html").with(MyServlet.class);
           serve("/my/*").with(MyServlet.class);
           serve("*.jpg").with(new MyServlet());
           // etc..
          }
        }
     
    This will traverse down the list of rules in lexical order. For example, a url "{@code /my/file.js}" (after it runs through the matching filters) will first be compared against the servlet mapping:
           serve("*.html").with(MyServlet.class);
     
    And failing that, it will descend to the next servlet mapping:
           serve("/my/*").with(MyServlet.class);
     
    Since this rule matches, Guice Servlet will dispatch to {@code MyServlet}. These two mapping rules can also be written in more compact form using varargs syntax:
           serve("*.html", "/my/*").with(MyServlet.class);
     
    This way you can map several URI patterns to the same servlet. A similar syntax is also available for filter mappings.

    Regular Expressions

    You can also map servlets (or filters) to URIs using regular expressions:
        serveRegex("(.)*ajax(.)*").with(MyAjaxServlet.class)
     
    This will map any URI containing the text "ajax" in it to {@code MyAjaxServlet}. Such as:
    • http://www.google.com/ajax.html
    • http://www.google.com/content/ajax/index
    • http://www.google.com/it/is_totally_ajaxian

    Initialization Parameters

    Servlets (and filters) allow you to pass in init params using the {@code } tag in web.xml. You can similarly pass in parameters to Servlets and filters registered in Guice-servlet using a {@link java.util.Map} of parameter name/value pairs. For example, to initialize {@code MyServlet} with two parameters ({@code name="Dhanji", site="google.com"}) you could write:
      Map<String, String> params = new HashMap<String, String>();
      params.put("name", "Dhanji");
      params.put("site", "google.com");
    
      ...
          serve("/*").with(MyServlet.class, params)
     

    Binding Keys

    You can also bind keys rather than classes. This lets you hide implementations with package-local visbility and expose them using only a Guice module and an annotation:
      ...
          filter("/*").through(Key.get(Filter.class, Fave.class));
     
    Where {@code Filter.class} refers to the Servlet API interface and {@code Fave.class} is a custom binding annotation. Elsewhere (in one of your own modules) you can bind this filter's implementation:
       bind(Filter.class).annotatedWith(Fave.class).to(MyFilterImpl.class);
     
    See {@link com.google.inject.Binder} for more information on binding syntax.

    Multiple Modules

    It is sometimes useful to capture servlet and filter mappings from multiple different modules. This is essential if you want to package and offer drop-in Guice plugins that provide servlet functionality.

    Guice Servlet allows you to register several instances of {@code ServletModule} to your injector. The order in which these modules are installed determines the dispatch order of filters and the precedence order of servlets. For example, if you had two servlet modules, {@code RpcModule} and {@code WebServiceModule} and they each contained a filter that mapped to the same URI pattern, {@code "/*"}:

    In {@code RpcModule}:

         filter("/*").through(RpcFilter.class);
     
    In {@code WebServiceModule}:
         filter("/*").through(WebServiceFilter.class);
     
    Then the order in which these filters are dispatched is determined by the order in which the modules are installed:
       install(new WebServiceModule());
       install(new RpcModule());
     
    In the case shown above {@code WebServiceFilter} will run first. @since 2.0]]>
    You should subclass this module to register servlets and filters in the {@link #configureServlets()} method. @author crazybob@google.com (Bob Lee) @author dhanji@gmail.com (Dhanji R. Prasanna)]]>
    There are some limitations:
    • Derived objects (i.e. anything marked @RequestScoped will not be transported.
    • State changes to the HttpServletRequest after this method is called will not be seen in the continued thread.
    • Only the HttpServletRequest, ServletContext and request parameter map are available in the continued thread. The response and session are not available.

    The returned callable will throw a {@link ScopingException} when called if the HTTP request scope is still active on the current thread. @param callable code to be executed in another thread, which depends on the request scope. @param seedMap the initial set of scoped instances for Guice to seed the request scope with. To seed a key with null, use {@code null} as the value. @return a callable that will invoke the given callable, making the request context available to it. @throws OutOfScopeException if this method is called from a non-request thread, or if the request has completed. @since 3.0]]> As opposed to {@link #continueRequest}, this method propagates all existing scoped objects. The primary use case is in server implementations where you can detach the request processing thread while waiting for data, and reattach to a different thread to finish processing at a later time.

    Because {@code HttpServletRequest} objects are not typically thread-safe, the callable returned by this method must not be run on a different thread until the current request scope has terminated. In other words, do not use this method to propagate the current request scope to worker threads that may run concurrently with the current thread.

    The returned callable will throw a {@link ScopingException} when called if the request scope being transferred is still active on a different thread. @param callable code to be executed in another thread, which depends on the request scope. @return a callable that will invoke the given callable, making the request context available to it. @throws OutOfScopeException if this method is called from a non-request thread, or if the request has completed.]]> The returned callable will throw a {@link ScopingException} when called if there is a request scope already active on the current thread. @param callable code to be executed which depends on the request scope. Typically in another thread, but not necessarily so. @param seedMap the initial set of scoped instances for Guice to seed the request scope with. To seed a key with null, use {@code null} as the value. @return a callable that when called will run inside the a request scope that exposes the instances in the {@code seedMap} as scoped keys. @since 3.0]]> any type to be returned by the visit method. Use {@link Void} with {@code return null} if no return type is needed. @since 2.0]]> any type to be returned by the visit method. Use {@link Void} with {@code return null} if no return type is needed. @since 2.0]]> any type to be returned by the visit method. Use {@link Void} with {@code return null} if no return type is needed. @author jessewilson@google.com (Jesse Wilson) @since 2.0]]> any type to be returned by the visit method. Use {@link Void} with {@code return null} if no return type is needed. @author jessewilson@google.com (Jesse Wilson) @since 2.0]]> any type to be returned by the visit method. Use {@link Void} with {@code return null} if no return type is needed. @author sberlin@gmail.com (Sam Berlin) @since 2.0]]> Use {@link #get} to build a freestanding dependency, or {@link InjectionPoint} to build one that's attached to a constructor, method or field. @author crazybob@google.com (Bob Lee) @author jessewilson@google.com (Jesse Wilson) @since 2.0]]> Tools might specially handle types they know about; {@code StackTraceElement} is a good example. Tools should simply call {@code toString()} on the source object if the type is unfamiliar.]]> The elements of a module can be inspected, validated and rewritten. Use {@link Elements#getElements(com.google.inject.Module[]) Elements.getElements()} to read the elements from a module, and {@link Elements#getModule(Iterable) Elements.getModule()} to rewrite them. This can be used for static analysis and generation of Guice modules.

    The elements of an injector can be inspected and exercised. Use {@link com.google.inject.Injector#getBindings Injector.getBindings()} to reflect on Guice injectors. @author jessewilson@google.com (Jesse Wilson) @author crazybob@google.com (Bob Lee) @since 2.0]]> {@code 0 - Binder.bind(), 1 - ModuleTwo.configure(), 2 - Binder.install(), 3 - ModuleOne.configure(), 4 - theRest(). }

    1 and 3 are returned.

    In the cases where stack trace is not available (i.e., the stack trace was not collected), it returns -1 for all module positions.]]> The {@link #getDeclaringSource() declaring source} refers to a location in source code that defines the Guice {@link Element element}. For example, if the element is created from a method annotated by {@literal @Provides}, the declaring source of element would be the method itself.

    The {@link #getStackTrace()} refers to the sequence of calls ends at one of {@link Binder} {@code bindXXX()} methods and eventually defines the element. Note that {@link #getStackTrace()} lists {@link StackTraceElement StackTraceElements} in reverse chronological order. The first element (index zero) is the last method call and the last element is the first method invocation. By default, the stack trace is not collected. The default behavior can be changed by setting the {@code guice_include_stack_traces} flag value. The value can be either {@code OFF}, {@code ONLY_FOR_DECLARING_SOURCE} or {@code COMPLETE}. Note that collecting stack traces for every binding can cause a performance hit when the injector is created.

    The sequence of class names of {@link Module modules} involved in the element creation can be retrieved by {@link #getModuleClassNames()}. Similar to {@link #getStackTrace()}, the order is reverse chronological. The first module (index 0) is the module that installs the {@link Element element}. The last module is the root module.

    In order to support the cases where a Guice {@link Element element} is created from another Guice {@link Element element} (original) (e.g., by {@link Element#applyTo()}), it also provides a reference to the original element source ({@link #getOriginalElementSource()}).]]> any type to be returned by the visit method. Use {@link Void} with {@code return null} if no return type is needed. @since 2.0]]> }), prefer the overload that includes a type literal. @param constructor any single constructor present on {@code type}. @since 3.0]]> } of the valid injection points.]]> } of the valid injection points.]]> } of the valid injection points.]]> } of the valid injection points.]]> } of the valid injection points.]]> requestInjection(serviceInstance); @author mikeward@google.com (Mike Ward) @since 2.0]]> bindInterceptor(Matchers.subclassesOf(MyAction.class), Matchers.annotatedWith(Transactional.class), new MyTransactionInterceptor()); or from an injectable type listener using {@link TypeEncounter#bindInterceptor(Matcher, org.aopalliance.intercept.MethodInterceptor[]) TypeEncounter.bindInterceptor()}. @author jessewilson@google.com (Jesse Wilson) @since 2.0]]> MembersInjector<PaymentService> membersInjector = getMembersInjector(PaymentService.class); @author crazybob@google.com (Bob Lee) @since 2.0]]> try { bindPropertiesFromFile(); } catch (IOException e) { addError(e); } @author crazybob@google.com (Bob Lee)]]> Tools might specially handle types they know about; {@code StackTraceElement} is a good example. Tools should simply call {@code toString()} on the source object if the type is unfamiliar. @param key one of the keys exposed by this module.]]> } is injected (as opposed to injecting {@code T} directly). @author jessewilson@google.com (Jesse Wilson) @since 2.0]]> Provider<PaymentService> paymentServiceProvider = getProvider(PaymentService.class); @author jessewilson@google.com (Jesse Wilson) @since 2.0]]> MUST call visitor.visit(binding).

    Due to issues with generics, the type parameters of this method do not relate to the type of the provider. In practice, the 'B' type will always be a supertype of 'T'.]]> When an extension binds a provider instance, the provider can implement this interface to allow users using the {@link Binding#acceptTargetVisitor(BindingTargetVisitor)} method to visit a custom visitor designed for that extension. A typical implementation within the extension would look like

     
     <V, B> V acceptExtensionVisitor(BindingTargetVisitor<B, V> visitor, ProviderInstanceBinding<? extends B> binding) {
       if(visitor instanceof MyCustomExtensionVisitor) {
         return ((MyCustomExtensionVisitor<B, V>)visitor).visitCustomExtension(customProperties, binding);
       } else {
         return visitor.visit(binding);
       }
     }
    'MyCustomExtensionVisitor' in the example above would be an interface the extension provides that users can implement in order to be notified of custom extension information. These visitor interfaces must extend from BindingTargetVisitor. @since 3.0 @author sameb@google.com (Sam Berlin)]]>
    If your {@link BindingTargetVisitor} implements this interface, bindings created by using {@code @Provides} will be visited through this interface. @since 4.0 @author sameb@google.com (Sam Berlin)]]> To perform the provision, call {@link ProvisionInvocation#provision()}. If you do not explicitly call provision, it will be automatically done after this method returns. It is an error to call provision more than once.]]> You must not call {@link Provider#get()} on the provider returned by {@link Binding#getProvider}, otherwise you will get confusing error messages.]]> Scope recordScope = new RecordScope(); bindScope(RecordScoped.class, new RecordScope()); @author jessewilson@google.com (Jesse Wilson) @since 2.0]]> } of the valid injection points.]]> requestStaticInjection(MyLegacyService.class); @author jessewilson@google.com (Jesse Wilson) @since 2.0]]> convertToTypes(Matchers.only(TypeLiteral.get(DateTime.class)), new DateTimeConverter()); @author jessewilson@google.com (Jesse Wilson) @since 2.0]]>
  • Guice created the instance the method is on
  • Neither the enclosing type nor the method is final
  • And the method is package-private or more accessible
  • @param methodMatcher matches methods the interceptor should apply to. For example: {@code annotatedWith(Transactional.class)}. @param interceptors to bind]]>
    the injectable type encountered @since 2.0]]> the injectable type]]> Useful for extra type checking, {@linkplain TypeEncounter#register(InjectionListener) registering injection listeners}, and {@linkplain TypeEncounter#bindInterceptor( com.google.inject.matcher.Matcher, org.aopalliance.intercept.MethodInterceptor[]) binding method interceptors}. @since 2.0]]> register(only(new TypeLiteral<PaymentService<CreditCard>>() {}), listener); @author jessewilson@google.com (Jesse Wilson) @since 2.0]]>
    bind(DataSource.class) .toProvider(fromSpring(DataSource.class, "dataSource")); ]]> This interface must be extended to use application-specific exception types. Such subinterfaces may not define new methods, but may narrow the exception type.
     public interface RemoteProvider<T> extends CheckedProvider<T> { 
       T get() throws CustomExceptionOne, CustomExceptionTwo;
     }
     

    When this type is bound using {@link ThrowingProviderBinder}, the value returned or exception thrown by {@link #get} will be scoped. As a consequence, {@link #get} will invoked at most once within each scope. @since 3.0]]> ThrowingProviderBinder.create(binder()) .bind(RemoteProvider.class, Customer.class) .providing(CustomerImpl.class); where CustomerImpl has a constructor annotated with ThrowingInject. @author sameb@google.com (Sam Berlin)]]> This interface must be extended to use application-specific exception types. Such subinterfaces may not define new methods:

     public interface RemoteProvider<T> extends ThrowingProvider<T, RemoteException> { }
     

    When this type is bound using {@link ThrowingProviderBinder}, the value returned or exception thrown by {@link #get} will be scoped. As a consequence, {@link #get} will invoked at most once within each scope. @author jmourits@google.com (Jerome Mourits) @author jessewilson@google.com (Jesse Wilson) @deprecated use {@link CheckedProvider} instead.]]> Builds a binding for a {@link CheckedProvider}.

    You can use a fluent API and custom providers:

    ThrowingProviderBinder.create(binder())
        .bind(RemoteProvider.class, Customer.class)
        .to(RemoteCustomerProvider.class)
        .in(RequestScope.class);
     
    or, you can use throwing provider methods:
    class MyModule extends AbstractModule {
       configure() {
         ThrowingProviderBinder.install(this, binder());
       }
       
       {@literal @}CheckedProvides(RemoteProvider.class)
       {@literal @}RequestScope
       Customer provideCustomer(FlakyCustomerCreator creator) throws RemoteException {
         return creator.getCustomerOrThrow();
       }
     }
     
    You also can declare that a CheckedProvider construct a particular class whose constructor throws an exception:
    ThrowingProviderBinder.create(binder())
        .bind(RemoteProvider.class, Customer.class)
        .providing(CustomerImpl.class)
        .in(RequestScope.class);
     
    @author jmourits@google.com (Jerome Mourits) @author jessewilson@google.com (Jesse Wilson) @author sameb@google.com (Sam Berlin)]]>
    Module functionalTestModule = Modules.override(new ProductionModule()).with(new TestModule());

    Prefer to write smaller modules that can be reused and tested without overrides. @param modules the modules whose bindings are open to be overridden]]> Module functionalTestModule = Modules.override(getProductionModules()).with(getTestModules());

    Prefer to write smaller modules that can be reused and tested without overrides. @param modules the modules whose bindings are open to be overridden]]>