关于辅助注入的页面解释了如何通过在构造函数中注释一些参数来完成辅助注入,@Assisted
但它没有解释@AssistedInject
注释的用途以及它与@Inject
. 该注释是否有某种关联?有什么区别?
2 回答
@Inject
并且@AssistedInject
两者都用于注释构造函数,这些构造函数应该使用正在使用的 Guice 模块的注入器调用。
唯一的区别是,@Inject
当工厂只有一个方法来创建类型时@AssistedInject
使用,而当工厂有多个这样的方法对应于该类型的多个构造函数时使用。更多的是帮助Guice区分这两种情况的细节。
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.