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.

    In the absence of an explicit binding for the target, linked bindings in child injectors create a binding for the target in the parent. Since this behavior can be surprising, it causes an error instead if explicit bindings are required. To avoid this error, add an explicit binding for the target, either in the child or the parent. @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 corresponding 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.) @since 4.0]]> 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.]]> Note: At present, it does not honor {@code @Module(includes=...)} directives.]]> Simple example:

    {@code
       Guice.createInjector(...other modules..., DaggerAdapter.from(new SomeDaggerAdapter()));
     }

    Some notes on usage and compatibility.

    • Dagger provider methods have a "SET_VALUES" provision mode not supported by Guice.
    • MapBindings are not yet implemented (pending).
    • Be careful about stateful modules. In contrast to Dagger (where components are expected to be recreated on-demand with new Module instances), Guice typically has a single injector with a long lifetime, so your module instance will be used throughout the lifetime of the entire app.
    • Dagger 1.x uses {@link @Singleton} for all scopes, including shorter-lived scopes like per-request or per-activity. Using modules written with Dagger 1.x usage in mind may result in mis-scoped objects.
    • Dagger 2.x supports custom scope annotations, but for use in Guice, a custom scope implementation must be registered in order to support the custom lifetime of that annotation.
    @author cgruber@google.com (Christian Gruber)]]>
    } and an instance node with the same {@link Key} and value of 42. @author bojand@google.com (Bojan Djordjevic) @since 4.0]]> 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) @since 4.0]]> 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)]]> A {@link StringMapKey} and {@link ClassMapKey} are provided for convenience with maps whose keys are strings or classes. For maps with enums or primitive types as keys, you must provide your own MapKey annotation, such as this one for an enum:

     {@literal @}MapKey(unwrapValue = true)
     {@literal @}Retention(RUNTIME)
     public {@literal @}interface MyCustomEnumKey {
       MyCustomEnum value();
     }
     
    You can also use the whole annotation as the key, if {@code unwrapValue=false}. When unwrapValue is false, the annotation type will be the key type for the injected map and the annotation instances will be the key values. If {@code unwrapValue=true}, the value() type will be the key type for injected map and the value() instances will be the keys values. @since 4.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() { 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) { ... }
     }
    If desired, {@link Collection}{@code >} can also be injected.

    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)]]> This is a convenience method, equivalent to doing {@code binder().scanModulesForAnnotatedMethods(MultibindingsScanner.scanner())}.]]> If your {@link BindingTargetVisitor} implements this interface, bindings created by using {@link Multibinder}, {@link MapBinder} or {@link OptionalBinderBinding} will be visited through this interface. @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.]]> It is an error to call this method without also calling one of the {@code to} methods on the returned binding builder.]]>

  • It allows a framework to define an injection point that may or may not be bound by users.
  • It allows a framework to supply a default value that can be changed by users.

    When an OptionalBinder is added, it will always supply the bindings: {@code Optional} and {@code Optional>}. If {@link #setBinding} or {@link #setDefault} are called, it will also bind {@code T}.

    {@code setDefault} is intended for use by frameworks that need a default value. User code can call {@code setBinding} to override the default. Warning: Even if setBinding is called, the default binding will still exist in the object graph. If it is a singleton, it will be instantiated in {@code Stage.PRODUCTION}.

    If setDefault or setBinding are linked to Providers, the Provider may return {@code null}. If it does, the Optional bindings will be absent. Binding setBinding to a Provider that returns null will not cause OptionalBinder to fall back to the setDefault binding.

    If neither setDefault nor setBinding are called, it will try to link to a user-supplied binding of the same type. If no binding exists, the optionals will be absent. Otherwise, if a user-supplied binding of that type exists, or if setBinding or setDefault are called, the optionals will return present if they are bound to a non-null value.

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

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

    
     public class FrameworkModule extends AbstractModule {
       protected void configure() {
         OptionalBinder.newOptionalBinder(binder(), Renamer.class);
       }
     }

    With this module, an {@link Optional}{@code } can now be injected. With no other bindings, the optional will be absent. Users can specify bindings in one of two ways:

    Option 1:

    
     public class UserRenamerModule extends AbstractModule {
       protected void configure() {
         bind(Renamer.class).to(ReplacingRenamer.class);
       }
     }

    or Option 2:

    
     public class UserRenamerModule extends AbstractModule {
       protected void configure() {
         OptionalBinder.newOptionalBinder(binder(), Renamer.class)
             .setBinding().to(ReplacingRenamer.class);
       }
     }
    With both options, the {@code Optional} will be present and supply the ReplacingRenamer.

    Default values can be supplied using:

    
     public class FrameworkModule extends AbstractModule {
       protected void configure() {
         OptionalBinder.newOptionalBinder(binder(), Key.get(String.class, LookupUrl.class))
             .setDefault().toInstance(DEFAULT_LOOKUP_URL);
       }
     }
    With the above module, code can inject an {@code @LookupUrl String} and it will supply the DEFAULT_LOOKUP_URL. A user can change this value by binding
    
     public class UserLookupModule extends AbstractModule {
       protected void configure() {
         OptionalBinder.newOptionalBinder(binder(), Key.get(String.class, LookupUrl.class))
             .setBinding().toInstance(CUSTOM_LOOKUP_URL);
       }
     }
    ... which will override the default value.

    If one module uses setDefault the only way to override the default is to use setBinding. It is an error for a user to specify the binding without using OptionalBinder if setDefault or setBinding are called. For example,

    
     public class FrameworkModule extends AbstractModule {
       protected void configure() {
         OptionalBinder.newOptionalBinder(binder(), Key.get(String.class, LookupUrl.class))
             .setDefault().toInstance(DEFAULT_LOOKUP_URL);
       }
     }
     public class UserLookupModule extends AbstractModule {
       protected void configure() {
         bind(Key.get(String.class, LookupUrl.class)).toInstance(CUSTOM_LOOKUP_URL);
       } 
     }
    ... would generate an error, because both the framework and the user are trying to bind {@code @LookupUrl String}. @author sameb@google.com (Sam Berlin) @since 4.0]]> The Binding's type will always match the type Optional's generic type. For example, if getKey returns a key of Optional<String>, then this will always return a Binding<String>.]]> The Binding's type will always match the type Optional's generic type. For example, if getKey returns a key of Optional<String>, then this will always return a Binding<String>.]]> Although OptionalBinders may be injected through a variety of types {@code T}, {@code Optional}, {@code Optional>}, etc..), an OptionalBinderBinding exists only on the Binding associated with the {@code Optional} key. Other bindings can be validated to be derived from this OptionalBinderBinding using {@link #containsElement}. @param The fully qualified type of the optional binding, including Optional. For example: {@code Optional}. @since 4.0 @author sameb@google.com (Sam Berlin)]]> {@literal @}ProvidesIntoMap {@literal @}StringMapKey("Foo") {@literal @}Named("plugins") Plugin provideFooUrl(FooManager fm) { returm fm.getPlugin(); } {@literal @}ProvidesIntoMap {@literal @}StringMapKey("Bar") {@literal @}Named("urls") Plugin provideBarUrl(BarManager bm) { return bm.getPlugin(); } will add two items to the {@code @Named("urls") Map} map. The key 'Foo' will map to the provideFooUrl method, and the key 'Bar' will map to the provideBarUrl method. The values are bound as providers and will be evaluated at injection time.

    Because the key is specified as an annotation, only Strings, Classes, enums, primitive types and annotation instances are supported as keys. @author sameb@google.com (Sam Berlin) @since 4.0]]> {@literal @}ProvidesIntoOptional(DEFAULT) {@literal @}Named("url") String provideFooUrl(FooManager fm) { returm fm.getUrl(); } {@literal @}ProvidesIntoOptional(ACTUAL) {@literal @}Named("url") String provideBarUrl(BarManager bm) { return bm.getUrl(); } will set the default value of {@code @Named("url") Optional} to foo's URL, and then override it to bar's URL. @author sameb@google.com (Sam Berlin) @since 4.0]]> {@literal @}ProvidesIntoSet {@literal @}Named("urls") String provideFooUrl(FooManager fm) { returm fm.getUrl(); } {@literal @}ProvidesIntoSet {@literal @}Named("urls") String provideBarUrl(BarManager bm) { return bm.getUrl(); } will add two items to the {@code @Named("urls") Set} set. The items are bound as providers and will be evaluated at injection time. @author sameb@google.com (Sam Berlin) @since 4.0]]> 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 https://github.com/google/guice/wiki/GuicePersist 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 request-scoped 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. The returned callable will block until the current thread has released the request scope. @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. @since 4.0]]> 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 com.google.inject.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 com.google.inject.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()}). @since 4.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]]> }), 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)]]> The injection point and annotation are provided in case the implementation wants to set the key based on the property of the annotation or if any additional preparation is needed for any of the dependencies. The annotation is guaranteed to be an instance of one the classes returned by {@link #annotationClasses}.]]> 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 module is intended for use in tests to reduce the code needed to bind local fields (usually mocks) for injection.

    The following rules are followed in determining how fields are bound using this module:

    • For each {@link Bind} annotated field of an object and its superclasses, this module will bind that field's type to that field's value at injector creation time. This includes both instance and static fields.
    • If {@link Bind#to} is specified, the field's value will be bound to the class specified by {@link Bind#to} instead of the field's actual type.
    • If a {@link BindingAnnotation} or {@link javax.inject.Qualifier} is present on the field, that field will be bound using that annotation via {@link AnnotatedBindingBuilder#annotatedWith}. For example, {@code bind(Foo.class).annotatedWith(BarAnnotation.class).toInstance(theValue)}. It is an error to supply more than one {@link BindingAnnotation} or {@link javax.inject.Qualifier}.
    • If the field is of type {@link Provider}, the field's value will be bound as a {@link Provider} using {@link LinkedBindingBuilder#toProvider} to the provider's parameterized type. For example, {@code Provider} binds to {@link Integer}. Attempting to bind a non-parameterized {@link Provider} without a {@link Bind#to} clause is an error.

    Example use:

    
     public class TestFoo {
       // bind(new TypeLiteral{@code >}() {}).toInstance(listOfObjects);
       {@literal @}Bind private List{@code } listOfObjects = Lists.of();
       
       // bind(String.class).toProvider(new Provider() { public String get() { return userName; }});
       {@literal @}Bind(lazy = true) private String userName;
    
       // bind(SuperClass.class).toInstance(aSubClass);
       {@literal @}Bind(to = SuperClass.class) private SubClass aSubClass = new SubClass();
    
       // bind(Object.class).annotatedWith(MyBindingAnnotation.class).toInstance(object2);
       {@literal @}Bind
       {@literal @}MyBindingAnnotation
       private String myString = "hello";
    
       // bind(Object.class).toProvider(myProvider);
       {@literal @}Bind private Provider{@code } myProvider = getProvider();
    
       {@literal @}Before public void setUp() {
         Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this);
       }
     }
     
    
     @see Bind
     @author eatnumber1@google.com (Russ Harmon)]]>
        
      
      
    
    
      
      
        
          
        
        
        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) @since 4.0]]> 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]]>