Can Guice inject Scala objects

2020-02-26 15:15发布

问题:

In Scala, can I use Guice to inject Scala objects?

For example, can I inject into s in the following object?

object GuiceSpec {
  @Inject
  val s: String = null

  def get() = s
}

回答1:

Some research on Google revealed that you can accomplish this as follows (the code that follows is a ScalaTest unit test):

import org.junit.runner.RunWith
import org.scalatest.WordSpec
import org.scalatest.matchers.MustMatchers
import org.scalatest.junit.JUnitRunner
import com.google.inject.Inject
import com.google.inject.Module
import com.google.inject.Binder
import com.google.inject.Guice
import uk.me.lings.scalaguice.ScalaModule

@RunWith(classOf[JUnitRunner])
class GuiceSpec extends WordSpec with MustMatchers {

  "Guice" must {
    "inject into Scala objects" in {
      val injector = Guice.createInjector(new ScalaModule() {
        def configure() {
          bind[String].toInstance("foo")
          bind[GuiceSpec.type].toInstance(GuiceSpec)
        }
      })
      injector.getInstance(classOf[String]) must equal("foo")
      GuiceSpec.get must equal("foo")
    }
  }
}

object GuiceSpec {
  @Inject
  var s: String = null

  def get() = s
}

This assumes you are using scala-guice and ScalaTest.



回答2:

The above answer is correct, but if you don't want to use ScalaGuice Extensions, you can do the following:

val injector = Guice.createInjector(new ScalaModule() {
    def configure() {
      bind[String].toInstance("foo")
    }

    @Provides
    def guiceSpecProvider: GuiceSpec.type = GuiceSpec
  })


标签: scala guice