Rip*_*tel 5 generics dependency-injection 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.
当你在那个时候建立cartService的情况下使用typeLiteral创建实例像
val cartService = injector.getInstance(Key.get(scalaguice.typeLiteral[CartService[Product]])
Run Code Online (Sandbox Code Playgroud)
如果您创建上面的实例,则无需创建模块.使用默认模块创建注入器(如果在应用程序级别的默认Module.scala中有任何其他绑定,则非常有用)
val appBuilder = new GuiceApplicationBuilder()
val injector = Guice.createInjector(appBuilder.applicationModule())
Run Code Online (Sandbox Code Playgroud)
如果你没有任何模块,你可以跳过传递模块作为参数并创建注入器而不传递任何模块
val injector = Guice.createInjector()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
403 次 |
| 最近记录: |