Generics Guice和Scala-泛型依赖项上的注入

Generics Guice和Scala-泛型依赖项上的注入,generics,scala,dependency-injection,guice,code-injection,Generics,Scala,Dependency Injection,Guice,Code Injection,我正在尝试使用Guice创建一个泛型特征的绑定 查看如何定义特征 trait Repository[T] 请参见trait实现 class DomainRepository extends Repository[Domain] 我在DomainPersistenceModule中的配置方法是: def configure() { bind(classOf[Repository[Domain]]) .annotatedWith(classOf[DomainDependency]

我正在尝试使用Guice创建一个泛型特征的绑定

查看如何定义
特征

trait Repository[T]
请参见
trait
实现

class DomainRepository extends Repository[Domain]
我在
DomainPersistenceModule
中的配置方法是:

def configure() {
   bind(classOf[Repository[Domain]])
     .annotatedWith(classOf[DomainDependency])
     .to(classOf[DomainRepository])
     .in(Scopes.SINGLETON)
}
其相关性将被注入的变量为:

  @Inject
  @DomainDependency
  var repository:Repository[Domain] = _
注射发生在这里:

val injector:Injector = Guice.createInjector(new PersistenceModule())

val persistenceService:PersistenceService =
        injector.getInstance(classOf[DomainPersistenceService])
错误是:

Caused by: com.google.inject.ConfigurationException: Guice configuration errors:

1) No implementation for repository.Repository<domain.Domain> annotated with @module.annotation.DomainDependency() was bound.
  while locating repository.Repository<domain.Domain> annotated with @module.annotation.DomainDependency()
    for field at service.persistence.DomainPersistenceService.repository(DomainPersistenceService.scala:19)
  while locating service.persistence.DomainPersistenceService
原因:com.google.inject.ConfigurationException:Guice配置错误:
1) 没有存储库的实现。绑定了使用@module.annotation.DomainDependency()注释的存储库。
查找repository.repository时使用@module.annotation.DomainDependency()注释
用于service.persistence.DomainPersistenceService.repository(DomainPersistenceService.scala:19)中的字段
查找service.persistence.DomainPersistenceService时
我错过什么了吗? 提前感谢

您需要这样的装订:

bind(new TypeLiteral[Repository[Domain]] {})
 .annotatedWith(classOf[DomainDependency])
 .to(classOf[DomainRepository])
 .in(Scopes.SINGLETON)
TypeLiteral
是一个特殊的类,允许您指定完整的参数化类型。基本上,不能用泛型类型参数实例化类

另外,看一看


如David所说,您需要一个
TypeLiteral
来绑定泛型类型(请记住,泛型类型只会被擦除到类中,而不会在运行时使用type参数)

另一种选择是使用类似于my library的东西,从Scala的
Manifest
s构建Guice所需的
TypeLiteral
s。如果混合使用
ScalaModule
trait,则可以执行以下操作:

bind[Repository[Domain]]
 .annotatedWith[DomainDependency]
 .to[DomainRepository]
 .in(Scopes.SINGLETON)