gpt4 book ai didi

generics - Guice 和 Scala - 泛型依赖注入(inject)

转载 作者:行者123 更新时间:2023-12-02 13:50:31 26 4
gpt4 key购买 nike

我正在尝试使用 Guice 创建通用特征的绑定(bind)

查看特征是如何定义的

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)依赖的变量是:

  @Inject
@DomainDependency
var repository:Repository[Domain] = _

注入(inject)发生在这里:

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

我错过了什么吗?提前致谢

最佳答案

您需要一个TypeLiteral像这样绑定(bind):

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

TypeLiteral 是一个特殊的类,允许您指定完整的参数化类型。基本上,您不能使用泛型类型参数实例化类。

此外,请查看 this answer

请参阅“如何使用泛型类型注入(inject)类?”在 Guice FAQ .

关于generics - Guice 和 Scala - 泛型依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6271435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com