在 Scala 中使用辅助注入绝对是可能的。如果 scala-guice 没有为它提供工具,你可以直接使用辅助注入 API:
trait Entity { ... }
class EntityImpl @Inject (
@Assisted assistedDep: AssistedDependency,
normalDep: NormalDependency
) extends Entity { ... }
trait EntityFactory {
def create(assistedDep: AssistedDependency): Entity
}
class YourModule extends AbstractModule with ScalaModule {
def configure {
install(new FactoryModuleBuilder()
.implement(classOf[Entity], classOf[EntityImpl])
.build(classOf[EntityFactory])
)
bind[NormalDependency].to[NormalDependencyImpl]
}
}
的确,它不是很漂亮,但它完成了工作。
此外,您绝对不应该删除guice-3.0.jar
. 当初为什么会想到?javax.inject.jar
包含 JSR-330 注释,guice-3.0.jar
包含 Guice 本身,并guice-assistedinject-3.0.jar
包含辅助注入扩展。如果您需要带有辅助注入支持的 Guice,所有这些罐子都很重要。