guice/Manual/Internals/InjectionPoints

Injection Points Constructor Selection

When Guice instantiates a type using its constructor, it decides which constructor to invoke by following these rules:

  1. Find and return an @Inject-annotated constructor
    • If any are @Inject(optional=true) constructors, record an error. Constructors may not be optional.
    • If there are multiple @Inject-annotated constructors, record an error. There may be at most one @Inject-annotated constructor.
    • If this constructor has binding annotations (like @Named), record an error. Binding annotations on the constructor's parameters are okay, but not on the constructor itself.
  2. Find and return a no-arguments constructor
    • If this constructor is private but the class is not private, record an error. Private constructors on non-private classes are not injectable without the @Inject annotation.
    • If this constructor itself has binding annotations (like @Named), record an error. Binding annotations on the constructor's parameters are okay, but not on the constructor itself.
  3. No suitable constructor was found. Record an error.

Injecting Fields and Methods

Injections are performed in a specific order. All fields are injected and then all methods. Within the fields, supertype fields are injected before subtype fields. Similarly, supertype methods are injected before subtype methods. What Gets Injected

Guice injects instance methods and fields of:

Guice injects static methods and fields of:

How Guice Injects

To inject a field, Guice will:

If the field injection is @Inject(optional=true) and the binding neither exists, nor can be created , the field injection is skipped.

To inject a method, Guice will:

If the method injection is optional and a parameter's binding neither exists nor can be created , the method injection will be skipped.

last edited 2009-12-13 03:34:15 by ysugimura