Google guice 的依赖注入在 Scala 中不起作用

Dependancy Injection of Google guice doesnt work in Scala

我想使用 DI google guice,它在 Java 中工作得很好,但在 scala 中不起作用。这是我的代码:

模块:

class ConfigModule extends AbstractModule{
  override def configure(): Unit = {

  }

  @Provides
  @Named("config")
  def getConfig(): Config = {
    new Config
  }
}

配置

   class Config {
    val config1: String = "Sample"
   }

服务

class Service(@Named("config") config:Config) {
    
      def read(): Unit = {
        println("Reading")
      }
    
    }

主要Class

object SampleJob {
  def main(args: Array[String]): Unit = {
    val injector = Guice.createInjector(new ConfigModule)
    val service = injector.getInstance(classOf[Service])
    service.read()
  }

}

错误:

1) Could not find a suitable constructor in com.job.Service. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
  at com.job.Service.class(Service.scala:7)
  while locating com.job.Service

我哪里弄错了?

更新:

class Service(@Inject @Named("config") config:Config) {

  def read(): Unit = {
    println("Reading")
  }

}

这也是returns同样的错误

Could not find a suitable constructor in com.job.Service. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
  at com.job.Service.class(Service.scala:8)
  while locating com.job.Service

错误告诉你发生了什么:

Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private

因此您需要添加 @Inject 注释...在 您的构造函数 上,例如 in tutorial.

而不是

class Service(@Inject @Named("config") config:Config) {

  def read(): Unit = {
    println("Reading")
  }

}

应该是

class Service @Inject() (@Named("config") config:Config) {

  def read(): Unit = {
    println("Reading")
  }

}