Guice 可以注入 Scala 对象吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13791815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:46:58  来源:igfitidea点击:

Can Guice inject Scala objects

scalaguice

提问by Hbf

In Scala, can I use Guiceto inject Scala objects?

在 Scala 中,我可以使用Guice注入 Scalaobject吗?

For example, can I inject into sin the following object?

例如,我可以注入到s以下对象中吗?

object GuiceSpec {
  @Inject
  val s: String = null

  def get() = s
}

回答by Hbf

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

Google 上的一些研究表明,您可以按如下方式完成此操作(以下代码是ScalaTest单元测试):

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-guiceand ScalaTest.

这假设您使用的是scala-guiceScalaTest

回答by Swayam

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

上面的回答是正确的,但是如果你不想使用ScalaGuiceExtensions,你可以执行以下操作:

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

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