【问题标题】:Can Guice inject Scala objectsGuice 可以注入 Scala 对象吗
【发布时间】:2012-12-09 21:05:20
【问题描述】:

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

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

object GuiceSpec {
  @Inject
  val s: String = null

  def get() = s
}

【问题讨论】:

    标签: scala guice


    【解决方案1】:

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

    假设您使用的是scala-guiceScalaTest

    【讨论】:

    【解决方案2】:

    上面的答案是正确的,但是如果你不想使用ScalaGuice Extensions,你可以这样做:

    val injector = Guice.createInjector(new ScalaModule() {
        def configure() {
          bind[String].toInstance("foo")
        }
    
        @Provides
        def guiceSpecProvider: GuiceSpec.type = GuiceSpec
      })
    

    【讨论】:

    • 你可以简单地在 configure() 中添加 requestInjection(guideSpec) 而不是 @Provides
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    相关资源
    最近更新 更多