Guice和Scala - 泛型依赖注入 [英] Guice And Scala - Injection on Generics Dependencies
本文介绍了Guice和Scala - 泛型依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用Guice创建一个通用特征的绑定
看看 trait
是如何定义
trait存储库[T]
查看 trait
实现
我的配置方法 DomainPersistenceModule $> c $ c>是:
def configure(){
bind(classOf [Repository [Domain]])
.annotatedWith(classOf [DomainDependency])
.to(classOf [DomainRepository])
.in(Scopes.SINGLETON)
}
将被注入的变量是:
@Inject
@DomainDependency
var repository:Repository [Domain] = _
注入发生在这里:
val注入器:注入器= Guice.createInjector(新的PersistenceModule())
val persistenceService:PersistenceService =
injector.getInstance(classOf [DomainPersistenceService])
错误是:
引起:com.google.inject.ConfigurationException:Guice配置错误:
1)没有对repository.Repository< domain.Domain>的实现。用@ module.annotation.DomainDependency()注解被绑定。
,同时定位repository.Repository< domain.Domain>使用@ module.annotation.DomainDependency()
对service.persistence.DomainPersistenceService.repository(DomainPersistenceService.scala:19)中的字段进行了注释
,同时查找service.persistence.DomainPersistenceService
我错过了什么吗?
提前致谢
解决方案您需要一个 TypeLiteral 如下所示绑定:
bind(new TypeLiteral [Repository [Domain]] {})
.annotatedWith(classOf [DomainDependency])
.to(classOf [DomainRepository])
.in (Scopes.SINGLETON)
请参阅如何使用泛型注入类?在 Guice常见问题中。
I'm trying to create a binding of a generic trait using Guice
See how the trait
is defined
trait Repository[T]
See the trait
implementation
class DomainRepository extends Repository[Domain]
My configure method in DomainPersistenceModule
is:
def configure() {
bind(classOf[Repository[Domain]])
.annotatedWith(classOf[DomainDependency])
.to(classOf[DomainRepository])
.in(Scopes.SINGLETON)
}
The variable whose dependence will be injected is:
@Inject
@DomainDependency
var repository:Repository[Domain] = _
The injection occurs here:
val injector:Injector = Guice.createInjector(new PersistenceModule())
val persistenceService:PersistenceService =
injector.getInstance(classOf[DomainPersistenceService])
The error is:
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
Am I missing something?
Thanks in advance
解决方案 You need a TypeLiteral binding like this:
bind(new TypeLiteral[Repository[Domain]] {})
.annotatedWith(classOf[DomainDependency])
.to(classOf[DomainRepository])
.in(Scopes.SINGLETON)
See "How to inject class with generic type?" in the Guice FAQ.
这篇关于Guice和Scala - 泛型依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文