Can Guice inject Scala objects

六眼飞鱼酱① 提交于 2019-11-30 11:17:14
Hbf

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.

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
  })
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!