2011-06-07 32 views
10

我試圖創建一個使用吉斯吉斯和Scala - 仿製藥的依賴注入

通用的特質

如何看trait定義的結合

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 

我缺少的東西? 在此先感謝

回答

15

你需要一個TypeLiteral結合這樣的:「?如何使用泛型類型注入類」

bind(new TypeLiteral[Repository[Domain]] {}) 
.annotatedWith(classOf[DomainDependency]) 
.to(classOf[DomainRepository]) 
.in(Scopes.SINGLETON) 

見在Guice FAQ

11

正如David所說,你需要一個TypeLiteral來綁定一個泛型類型(記住 - 泛型類型被刪除到只有類,沒有運行時類型參數)。

另一種選擇是類似於我的Scala Guice庫來構建從斯卡拉的Manifest s的Guice所需的TypeLiteral。如果你混入ScalaModule的特質,那麼你就可以做類似的事情:

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