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