Guice可以注入Scala对象 [英] Can Guice inject Scala objects

查看:81
本文介绍了Guice可以注入Scala对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

object GuiceSpec {
  @Inject
  val s: String = null

  def get() = s
}

推荐答案

在Google上进行的一些研究表明,您可以按以下步骤完成此操作(以下代码是

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
}

这假定您正在使用 scala-guice 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆