小编Rip*_*tel的帖子

Scala - 当依赖类也使用相同的泛型类型时,使用guice注入泛型类型

我想使用Guice为Generic类型注入依赖.在scala中查找以下示例来复制问题.

ProductModel.scala

trait BaseProduct  

case class Product() extends BaseProduct 
Run Code Online (Sandbox Code Playgroud)

CartService.scala

class CartService[A <: BaseProduct] @Inject()(productService : ProductService[A]) {
 def getCartItems = productService.getProduct
}
Run Code Online (Sandbox Code Playgroud)

ProductService.scala

class ProductService[A]{
 def getProduct = println("ProductService")
}
Run Code Online (Sandbox Code Playgroud)

Main.scala

object Main extends App {

  val injector = Guice.createInjector(new ShoppingModule)
  val cartService = injector.getInstance(classOf[CartService[Product]])
  cartService.getCartItems
}

class ShoppingModule extends AbstractModule with ScalaModule {
  override def configure(): Unit = {
    bind[BaseProduct].to(scalaguice.typeLiteral[Product])
  }
}
Run Code Online (Sandbox Code Playgroud)

运行此Main.scala应用程序时出现以下错误.

service.ProductService<A> cannot be used as a key; It is not fully specified.
Run Code Online (Sandbox Code Playgroud)

我尝试使用codingwell库进行绑定.但它无法识别ProductService Type.

generics dependency-injection scala guice

5
推荐指数
1
解决办法
403
查看次数

标签 统计

dependency-injection ×1

generics ×1

guice ×1

scala ×1