4

The page regarding assisted injection explains how assisted injection can be done by annotating some parameters in the constructor with @Assisted but it does not explain what the @AssistedInject annotation is for and how it differs from @Inject. Is that annotation somehow related? What are the differences?

rgrinberg
  • 9,638
  • 7
  • 27
  • 44

2 Answers2

4

@Inject and @AssistedInject both are used to annotate constructors which are supposed to be invoked using the injector of the Guice module being used.

The only difference is, @Inject is used when the factory has only one method to create the type, while @AssistedInject is used when the factory has multiple such methods corresponding to multiple constructors for the type. It is more of a detail to assist Guice in distinguishing the two cases.

durron597
  • 31,968
  • 17
  • 99
  • 158
2

From http://google-guice.googlecode.com/git/javadoc/com/google/inject/assistedinject/AssistedInject.html

When used in tandem with FactoryModuleBuilder, constructors annotated with @AssistedInject indicate that multiple constructors can be injected, each with different parameters. AssistedInject annotations should not be mixed with @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 FactoryProvider, constructors annotated with @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.

condit
  • 10,852
  • 2
  • 41
  • 60