Can Guice inject Scala objects

Hbf picture Hbf · Dec 9, 2012 · Viewed 15.2k times · Source

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
}

Answer

Hbf picture Hbf · Dec 9, 2012

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.