加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Guice可以注入Scala对象

发布时间:2020-12-16 09:20:11 所属栏目:安全 来源:网络整理
导读:在 Scala中,我可以使用 Guice注入Scala对象吗? 例如,我可以在以下对象中注入s? object GuiceSpec { @Inject val s: String = null def get() = s} 解决方法 对Google的一些研究(见 this post)表明可以如下完成(下面的代码是 ScalaTest单元测试): import o
在 Scala中,我可以使用 Guice注入Scala对象吗?

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

object GuiceSpec {
  @Inject
  val s: String = null

  def get() = s
}

解决方法

对Google的一些研究(见 this post)表明可以如下完成(下面的代码是 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
  val s: String = null

  def get() = s
}

这假定您正在使用scala-guice和ScalaTest.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读