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

Saa*_*wan 1 dependency-injection scala guice

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

模块:

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

  }

  @Provides
  @Named("config")
  def getConfig(): Config = {
    new Config
  }
}
Run Code Online (Sandbox Code Playgroud)

配置

   class Config {
    val config1: String = "Sample"
   }
Run Code Online (Sandbox Code Playgroud)

服务

class Service(@Named("config") config:Config) {
    
      def read(): Unit = {
        println("Reading")
      }
    
    }
Run Code Online (Sandbox Code Playgroud)

主班

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

}
Run Code Online (Sandbox Code Playgroud)

错误:

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
Run Code Online (Sandbox Code Playgroud)

我哪里弄错了?

更新:

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

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

}
Run Code Online (Sandbox Code Playgroud)

这也会返回相同的错误

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
Run Code Online (Sandbox Code Playgroud)

Mat*_*zok 5

该错误告诉您发生了什么:

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

因此,您需要在构造函数@Inject上添加注释...,如教程中所示

代替

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

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

}
Run Code Online (Sandbox Code Playgroud)

它应该是

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

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

}
Run Code Online (Sandbox Code Playgroud)