Home | History | Annotate | Download | only in inject
      1 /*
      2  * Copyright (C) 2007 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.inject;
     18 
     19 import com.google.inject.binder.AnnotatedBindingBuilder;
     20 import com.google.inject.binder.AnnotatedConstantBindingBuilder;
     21 import com.google.inject.binder.LinkedBindingBuilder;
     22 import com.google.inject.matcher.Matcher;
     23 import com.google.inject.spi.Dependency;
     24 import com.google.inject.spi.Message;
     25 import com.google.inject.spi.ModuleAnnotatedMethodScanner;
     26 import com.google.inject.spi.ProvisionListener;
     27 import com.google.inject.spi.TypeConverter;
     28 import com.google.inject.spi.TypeListener;
     29 
     30 import java.lang.annotation.Annotation;
     31 import java.lang.reflect.Method;
     32 import java.lang.reflect.Proxy;
     33 
     34 /**
     35  * Collects configuration information (primarily <i>bindings</i>) which will be
     36  * used to create an {@link Injector}. Guice provides this object to your
     37  * application's {@link Module} implementors so they may each contribute
     38  * their own bindings and other registrations.
     39  *
     40  * <h3>The Guice Binding EDSL</h3>
     41  *
     42  * Guice uses an <i>embedded domain-specific language</i>, or EDSL, to help you
     43  * create bindings simply and readably.  This approach is great for overall
     44  * usability, but it does come with a small cost: <b>it is difficult to
     45  * learn how to use the Binding EDSL by reading
     46  * method-level javadocs</b>.  Instead, you should consult the series of
     47  * examples below.  To save space, these examples omit the opening
     48  * {@code binder}, just as you will if your module extends
     49  * {@link AbstractModule}.
     50  *
     51  * <pre>
     52  *     bind(ServiceImpl.class);</pre>
     53  *
     54  * This statement does essentially nothing; it "binds the {@code ServiceImpl}
     55  * class to itself" and does not change Guice's default behavior.  You may still
     56  * want to use this if you prefer your {@link Module} class to serve as an
     57  * explicit <i>manifest</i> for the services it provides.  Also, in rare cases,
     58  * Guice may be unable to validate a binding at injector creation time unless it
     59  * is given explicitly.
     60  *
     61  * <pre>
     62  *     bind(Service.class).to(ServiceImpl.class);</pre>
     63  *
     64  * Specifies that a request for a {@code Service} instance with no binding
     65  * annotations should be treated as if it were a request for a
     66  * {@code ServiceImpl} instance. This <i>overrides</i> the function of any
     67  * {@link ImplementedBy @ImplementedBy} or {@link ProvidedBy @ProvidedBy}
     68  * annotations found on {@code Service}, since Guice will have already
     69  * "moved on" to {@code ServiceImpl} before it reaches the point when it starts
     70  * looking for these annotations.
     71  *
     72  * <pre>
     73  *     bind(Service.class).toProvider(ServiceProvider.class);</pre>
     74  *
     75  * In this example, {@code ServiceProvider} must extend or implement
     76  * {@code Provider<Service>}. This binding specifies that Guice should resolve
     77  * an unannotated injection request for {@code Service} by first resolving an
     78  * instance of {@code ServiceProvider} in the regular way, then calling
     79  * {@link Provider#get get()} on the resulting Provider instance to obtain the
     80  * {@code Service} instance.
     81  *
     82  * <p>The {@link Provider} you use here does not have to be a "factory"; that
     83  * is, a provider which always <i>creates</i> each instance it provides.
     84  * However, this is generally a good practice to follow.  You can then use
     85  * Guice's concept of {@link Scope scopes} to guide when creation should happen
     86  * -- "letting Guice work for you".
     87  *
     88  * <pre>
     89  *     bind(Service.class).annotatedWith(Red.class).to(ServiceImpl.class);</pre>
     90  *
     91  * Like the previous example, but only applies to injection requests that use
     92  * the binding annotation {@code @Red}.  If your module also includes bindings
     93  * for particular <i>values</i> of the {@code @Red} annotation (see below),
     94  * then this binding will serve as a "catch-all" for any values of {@code @Red}
     95  * that have no exact match in the bindings.
     96  *
     97  * <pre>
     98  *     bind(ServiceImpl.class).in(Singleton.class);
     99  *     // or, alternatively
    100  *     bind(ServiceImpl.class).in(Scopes.SINGLETON);</pre>
    101  *
    102  * Either of these statements places the {@code ServiceImpl} class into
    103  * singleton scope.  Guice will create only one instance of {@code ServiceImpl}
    104  * and will reuse it for all injection requests of this type.  Note that it is
    105  * still possible to bind another instance of {@code ServiceImpl} if the second
    106  * binding is qualified by an annotation as in the previous example.  Guice is
    107  * not overly concerned with <i>preventing</i> you from creating multiple
    108  * instances of your "singletons", only with <i>enabling</i> your application to
    109  * share only one instance if that's all you tell Guice you need.
    110  *
    111  * <p><b>Note:</b> a scope specified in this way <i>overrides</i> any scope that
    112  * was specified with an annotation on the {@code ServiceImpl} class.
    113  *
    114  * <p>Besides {@link Singleton}/{@link Scopes#SINGLETON}, there are
    115  * servlet-specific scopes available in
    116  * {@code com.google.inject.servlet.ServletScopes}, and your Modules can
    117  * contribute their own custom scopes for use here as well.
    118  *
    119  * <pre>
    120  *     bind(new TypeLiteral&lt;PaymentService&lt;CreditCard>>() {})
    121  *         .to(CreditCardPaymentService.class);</pre>
    122  *
    123  * This admittedly odd construct is the way to bind a parameterized type. It
    124  * tells Guice how to honor an injection request for an element of type
    125  * {@code PaymentService<CreditCard>}. The class
    126  * {@code CreditCardPaymentService} must implement the
    127  * {@code PaymentService<CreditCard>} interface.  Guice cannot currently bind or
    128  * inject a generic type, such as {@code Set<E>}; all type parameters must be
    129  * fully specified.
    130  *
    131  * <pre>
    132  *     bind(Service.class).toInstance(new ServiceImpl());
    133  *     // or, alternatively
    134  *     bind(Service.class).toInstance(SomeLegacyRegistry.getService());</pre>
    135  *
    136  * In this example, your module itself, <i>not Guice</i>, takes responsibility
    137  * for obtaining a {@code ServiceImpl} instance, then asks Guice to always use
    138  * this single instance to fulfill all {@code Service} injection requests.  When
    139  * the {@link Injector} is created, it will automatically perform field
    140  * and method injection for this instance, but any injectable constructor on
    141  * {@code ServiceImpl} is simply ignored.  Note that using this approach results
    142  * in "eager loading" behavior that you can't control.
    143  *
    144  * <pre>
    145  *     bindConstant().annotatedWith(ServerHost.class).to(args[0]);</pre>
    146  *
    147  * Sets up a constant binding. Constant injections must always be annotated.
    148  * When a constant binding's value is a string, it is eligile for conversion to
    149  * all primitive types, to {@link Enum#valueOf(Class, String) all enums}, and to
    150  * {@link Class#forName class literals}. Conversions for other types can be
    151  * configured using {@link #convertToTypes(Matcher, TypeConverter)
    152  * convertToTypes()}.
    153  *
    154  * <pre>
    155  *   {@literal @}Color("red") Color red; // A member variable (field)
    156  *    . . .
    157  *     red = MyModule.class.getDeclaredField("red").getAnnotation(Color.class);
    158  *     bind(Service.class).annotatedWith(red).to(RedService.class);</pre>
    159  *
    160  * If your binding annotation has parameters you can apply different bindings to
    161  * different specific values of your annotation.  Getting your hands on the
    162  * right instance of the annotation is a bit of a pain -- one approach, shown
    163  * above, is to apply a prototype annotation to a field in your module class, so
    164  * that you can read this annotation instance and give it to Guice.
    165  *
    166  * <pre>
    167  *     bind(Service.class)
    168  *         .annotatedWith(Names.named("blue"))
    169  *         .to(BlueService.class);</pre>
    170  *
    171  * Differentiating by names is a common enough use case that we provided a
    172  * standard annotation, {@link com.google.inject.name.Named @Named}.  Because of
    173  * Guice's library support, binding by name is quite easier than in the
    174  * arbitrary binding annotation case we just saw.  However, remember that these
    175  * names will live in a single flat namespace with all the other names used in
    176  * your application.
    177  *
    178  * <pre>
    179  *     Constructor<T> loneCtor = getLoneCtorFromServiceImplViaReflection();
    180  *     bind(ServiceImpl.class)
    181  *         .toConstructor(loneCtor);</pre>
    182  *
    183  * In this example, we directly tell Guice which constructor to use in a concrete
    184  * class implementation. It means that we do not need to place {@literal @}Inject
    185  * on any of the constructors and that Guice treats the provided constructor as though
    186  * it were annotated so. It is useful for cases where you cannot modify existing
    187  * classes and is a bit simpler than using a {@link Provider}.
    188  *
    189  * <p>The above list of examples is far from exhaustive.  If you can think of
    190  * how the concepts of one example might coexist with the concepts from another,
    191  * you can most likely weave the two together.  If the two concepts make no
    192  * sense with each other, you most likely won't be able to do it.  In a few
    193  * cases Guice will let something bogus slip by, and will then inform you of
    194  * the problems at runtime, as soon as you try to create your Injector.
    195  *
    196  * <p>The other methods of Binder such as {@link #bindScope},
    197  * {@link #bindInterceptor}, {@link #install}, {@link #requestStaticInjection},
    198  * {@link #addError} and {@link #currentStage} are not part of the Binding EDSL;
    199  * you can learn how to use these in the usual way, from the method
    200  * documentation.
    201  *
    202  * @author crazybob (at) google.com (Bob Lee)
    203  * @author jessewilson (at) google.com (Jesse Wilson)
    204  * @author kevinb (at) google.com (Kevin Bourrillion)
    205  */
    206 public interface Binder {
    207 
    208   /*if[AOP]*/
    209   /**
    210    * Binds method interceptor[s] to methods matched by class and method matchers. A method is
    211    * eligible for interception if:
    212    *
    213    * <ul>
    214    *  <li>Guice created the instance the method is on</li>
    215    *  <li>Neither the enclosing type nor the method is final</li>
    216    *  <li>And the method is package-private, protected, or public</li>
    217    * </ul>
    218    *
    219    * @param classMatcher matches classes the interceptor should apply to. For
    220    *     example: {@code only(Runnable.class)}.
    221    * @param methodMatcher matches methods the interceptor should apply to. For
    222    *     example: {@code annotatedWith(Transactional.class)}.
    223    * @param interceptors to bind.  The interceptors are called in the order they
    224    *     are given.
    225    */
    226   void bindInterceptor(Matcher<? super Class<?>> classMatcher,
    227       Matcher<? super Method> methodMatcher,
    228       org.aopalliance.intercept.MethodInterceptor... interceptors);
    229   /*end[AOP]*/
    230 
    231   /**
    232    * Binds a scope to an annotation.
    233    */
    234   void bindScope(Class<? extends Annotation> annotationType, Scope scope);
    235 
    236   /**
    237    * See the EDSL examples at {@link Binder}.
    238    */
    239   <T> LinkedBindingBuilder<T> bind(Key<T> key);
    240 
    241   /**
    242    * See the EDSL examples at {@link Binder}.
    243    */
    244   <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral);
    245 
    246   /**
    247    * See the EDSL examples at {@link Binder}.
    248    */
    249   <T> AnnotatedBindingBuilder<T> bind(Class<T> type);
    250 
    251   /**
    252    * See the EDSL examples at {@link Binder}.
    253    */
    254   AnnotatedConstantBindingBuilder bindConstant();
    255 
    256   /**
    257    * Upon successful creation, the {@link Injector} will inject instance fields
    258    * and methods of the given object.
    259    *
    260    * @param type of instance
    261    * @param instance for which members will be injected
    262    * @since 2.0
    263    */
    264   <T> void requestInjection(TypeLiteral<T> type, T instance);
    265 
    266   /**
    267    * Upon successful creation, the {@link Injector} will inject instance fields
    268    * and methods of the given object.
    269    *
    270    * @param instance for which members will be injected
    271    * @since 2.0
    272    */
    273   void requestInjection(Object instance);
    274 
    275   /**
    276    * Upon successful creation, the {@link Injector} will inject static fields
    277    * and methods in the given classes.
    278    *
    279    * @param types for which static members will be injected
    280    */
    281   void requestStaticInjection(Class<?>... types);
    282 
    283   /**
    284    * Uses the given module to configure more bindings.
    285    */
    286   void install(Module module);
    287 
    288   /**
    289    * Gets the current stage.
    290    */
    291   Stage currentStage();
    292 
    293   /**
    294    * Records an error message which will be presented to the user at a later
    295    * time. Unlike throwing an exception, this enable us to continue
    296    * configuring the Injector and discover more errors. Uses {@link
    297    * String#format(String, Object[])} to insert the arguments into the
    298    * message.
    299    */
    300   void addError(String message, Object... arguments);
    301 
    302   /**
    303    * Records an exception, the full details of which will be logged, and the
    304    * message of which will be presented to the user at a later
    305    * time. If your Module calls something that you worry may fail, you should
    306    * catch the exception and pass it into this.
    307    */
    308   void addError(Throwable t);
    309 
    310   /**
    311    * Records an error message to be presented to the user at a later time.
    312    *
    313    * @since 2.0
    314    */
    315   void addError(Message message);
    316 
    317   /**
    318    * Returns the provider used to obtain instances for the given injection key.
    319    * The returned provider will not be valid until the {@link Injector} has been
    320    * created. The provider will throw an {@code IllegalStateException} if you
    321    * try to use it beforehand.
    322    *
    323    * @since 2.0
    324    */
    325   <T> Provider<T> getProvider(Key<T> key);
    326 
    327   /**
    328    * Returns the provider used to obtain instances for the given injection key.
    329    * The returned provider will be attached to the injection point and will
    330    * follow the nullability specified in the dependency.
    331    * Additionally, the returned provider will not be valid until the {@link Injector}
    332    * has been created. The provider will throw an {@code IllegalStateException} if you
    333    * try to use it beforehand.
    334    *
    335    * @since 4.0
    336    */
    337   <T> Provider<T> getProvider(Dependency<T> dependency);
    338 
    339   /**
    340    * Returns the provider used to obtain instances for the given injection type.
    341    * The returned provider will not be valid until the {@link Injector} has been
    342    * created. The provider will throw an {@code IllegalStateException} if you
    343    * try to use it beforehand.
    344    *
    345    * @since 2.0
    346    */
    347   <T> Provider<T> getProvider(Class<T> type);
    348 
    349   /**
    350    * Returns the members injector used to inject dependencies into methods and fields on instances
    351    * of the given type {@code T}. The returned members injector will not be valid until the main
    352    * {@link Injector} has been created. The members injector will throw an {@code
    353    * IllegalStateException} if you try to use it beforehand.
    354    *
    355    * @param typeLiteral type to get members injector for
    356    * @since 2.0
    357    */
    358   <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral);
    359 
    360   /**
    361    * Returns the members injector used to inject dependencies into methods and fields on instances
    362    * of the given type {@code T}. The returned members injector will not be valid until the main
    363    * {@link Injector} has been created. The members injector will throw an {@code
    364    * IllegalStateException} if you try to use it beforehand.
    365    *
    366    * @param type type to get members injector for
    367    * @since 2.0
    368    */
    369   <T> MembersInjector<T> getMembersInjector(Class<T> type);
    370 
    371   /**
    372    * Binds a type converter. The injector will use the given converter to
    373    * convert string constants to matching types as needed.
    374    *
    375    * @param typeMatcher matches types the converter can handle
    376    * @param converter converts values
    377    * @since 2.0
    378    */
    379   void convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher,
    380       TypeConverter converter);
    381 
    382   /**
    383    * Registers a listener for injectable types. Guice will notify the listener when it encounters
    384    * injectable types matched by the given type matcher.
    385    *
    386    * @param typeMatcher that matches injectable types the listener should be notified of
    387    * @param listener for injectable types matched by typeMatcher
    388    * @since 2.0
    389    */
    390   void bindListener(Matcher<? super TypeLiteral<?>> typeMatcher,
    391       TypeListener listener);
    392 
    393   /**
    394    * Registers listeners for provisioned objects. Guice will notify the
    395    * listeners just before and after the object is provisioned. Provisioned
    396    * objects that are also injectable (everything except objects provided
    397    * through Providers) can also be notified through TypeListeners registered in
    398    * {@link #bindListener}.
    399    *
    400    * @param bindingMatcher that matches bindings of provisioned objects the listener
    401    *          should be notified of
    402    * @param listeners for provisioned objects matched by bindingMatcher
    403    * @since 4.0
    404    */
    405   void bindListener(Matcher<? super Binding<?>> bindingMatcher, ProvisionListener... listeners);
    406 
    407   /**
    408    * Returns a binder that uses {@code source} as the reference location for
    409    * configuration errors. This is typically a {@link StackTraceElement}
    410    * for {@code .java} source but it could any binding source, such as the
    411    * path to a {@code .properties} file.
    412    *
    413    * @param source any object representing the source location and has a
    414    *     concise {@link Object#toString() toString()} value
    415    * @return a binder that shares its configuration with this binder
    416    * @since 2.0
    417    */
    418   Binder withSource(Object source);
    419 
    420   /**
    421    * Returns a binder that skips {@code classesToSkip} when identify the
    422    * calling code. The caller's {@link StackTraceElement} is used to locate
    423    * the source of configuration errors.
    424    *
    425    * @param classesToSkip library classes that create bindings on behalf of
    426    *      their clients.
    427    * @return a binder that shares its configuration with this binder.
    428    * @since 2.0
    429    */
    430   Binder skipSources(Class... classesToSkip);
    431 
    432   /**
    433    * Creates a new private child environment for bindings and other configuration. The returned
    434    * binder can be used to add and configuration information in this environment. See {@link
    435    * PrivateModule} for details.
    436    *
    437    * @return a binder that inherits configuration from this binder. Only exposed configuration on
    438    *      the returned binder will be visible to this binder.
    439    * @since 2.0
    440    */
    441   PrivateBinder newPrivateBinder();
    442 
    443   /**
    444    * Instructs the Injector that bindings must be listed in a Module in order to
    445    * be injected. Classes that are not explicitly bound in a module cannot be
    446    * injected. Bindings created through a linked binding
    447    * (<code>bind(Foo.class).to(FooImpl.class)</code>) are allowed, but the
    448    * implicit binding (<code>FooImpl</code>) cannot be directly injected unless
    449    * it is also explicitly bound (<code>bind(FooImpl.class)</code>).
    450    * <p>
    451    * Tools can still retrieve bindings for implicit bindings (bindings created
    452    * through a linked binding) if explicit bindings are required, however
    453    * {@link Binding#getProvider} will fail.
    454    * <p>
    455    * By default, explicit bindings are not required.
    456    * <p>
    457    * If a parent injector requires explicit bindings, then all child injectors
    458    * (and private modules within that injector) also require explicit bindings.
    459    * If a parent does not require explicit bindings, a child injector or private
    460    * module may optionally declare itself as requiring explicit bindings. If it
    461    * does, the behavior is limited only to that child or any grandchildren. No
    462    * siblings of the child will require explicit bindings.
    463    * <p>
    464    * In the absence of an explicit binding for the target, linked bindings in
    465    * child injectors create a binding for the target in the parent. Since this
    466    * behavior can be surprising, it causes an error instead if explicit bindings
    467    * are required. To avoid this error, add an explicit binding for the target,
    468    * either in the child or the parent.
    469    *
    470    * @since 3.0
    471    */
    472   void requireExplicitBindings();
    473 
    474   /**
    475    * Prevents Guice from constructing a {@link Proxy} when a circular dependency
    476    * is found.  By default, circular proxies are not disabled.
    477    * <p>
    478    * If a parent injector disables circular proxies, then all child injectors
    479    * (and private modules within that injector) also disable circular proxies.
    480    * If a parent does not disable circular proxies, a child injector or private
    481    * module may optionally declare itself as disabling circular proxies. If it
    482    * does, the behavior is limited only to that child or any grandchildren. No
    483    * siblings of the child will disable circular proxies.
    484    *
    485    * @since 3.0
    486    */
    487   void disableCircularProxies();
    488 
    489   /**
    490    * Requires that a {@literal @}{@link Inject} annotation exists on a constructor in order for
    491    * Guice to consider it an eligible injectable class. By default, Guice will inject classes that
    492    * have a no-args constructor if no {@literal @}{@link Inject} annotation exists on any
    493    * constructor.
    494    * <p>
    495    * If the class is bound using {@link LinkedBindingBuilder#toConstructor}, Guice will still inject
    496    * that constructor regardless of annotations.
    497    *
    498    * @since 4.0
    499    */
    500   void requireAtInjectOnConstructors();
    501 
    502   /**
    503    * Requires that Guice finds an exactly matching binding annotation.  This disables the
    504    * error-prone feature in Guice where it can substitute a binding for
    505    * <code>{@literal @}Named Foo</code> when attempting to inject
    506    * <code>{@literal @}Named("foo") Foo</code>.
    507    *
    508    * @since 4.0
    509    */
    510   void requireExactBindingAnnotations();
    511 
    512   /**
    513    * Adds a scanner that will look in all installed modules for annotations the scanner can parse,
    514    * and binds them like {@literal @}Provides methods. Scanners apply to all modules installed in
    515    * the injector. Scanners installed in child injectors or private modules do not impact modules in
    516    * siblings or parents, however scanners installed in parents do apply to all child injectors and
    517    * private modules.
    518    *
    519    * @since 4.0
    520    */
    521   void scanModulesForAnnotatedMethods(ModuleAnnotatedMethodScanner scanner);
    522 }
    523