scala:如何在guice模块中注入

scala: how to inject inside guice module

我是 guice 的新手,这是我的代码

trait MyRepository

class MyRepositoryImp extends MyRepository

trait MyService

class MyServiceImp @Inject()(myRepository:MyRepository) extends MyService

class Demo @Inject(myService:MyService)

class RepositoryModule extends AbstractModule {

override protected def configure(): Unit = {
    bind(classOf[MyRepository]).toInstance(new MyRepositoryImpl)

  }
}

class ServiceModule extends AbstractModule {

override protected def configure(): Unit = {
    bind(classOf[MyService]).toInstance(new MyService(//what should i pass in here?))

  }
}

我的问题是 ServiceModule 如何在 MyService 构造函数中传递注入的 MyRepository 参数

尝试使用 @Provides 注释

import com.google.inject.{AbstractModule, Guice, Inject, Injector, Provides}
import scala.jdk.CollectionConverters._

trait MyRepository {}
class MyRepositoryImp extends MyRepository {}
trait MyService {}
class MyServiceImp @Inject() (myRepository: MyRepository) extends MyService {}
class Demo @Inject() (myService: MyService) { println("Woohoo, I am wired!") }

class Module extends AbstractModule {
  @Provides def repository: MyRepository = new MyRepositoryImp
  @Provides def service(repo: MyRepository): MyService = new MyServiceImp(repo)
  @Provides def demo(service: MyService): Demo = new Demo(service)
}

object guiceExample extends App {
  val injector: Injector = Guice.createInjector(List(new Module).asJava)
  val demo = injector.getInstance(classOf[Demo])
}

输出 Woohoo, I am wired!.