Hbf
Hbf

Reputation: 3114

Can Guice inject Scala objects

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
}

Upvotes: 24

Views: 16655

Answers (2)

Hbf
Hbf

Reputation: 3114

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.

Upvotes: 21

Swayam
Swayam

Reputation: 600

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
  })

Upvotes: 2

Related Questions