2012-12-09 81 views
17

在Scala中,我可以使用Guice来注入Scala object s吗?Can Guice可以注入Scala对象

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

object GuiceSpec { 
    @Inject 
    val s: String = null 

    def get() = s 
} 

回答

16

在谷歌(见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-guiceScalaTest

+0

在后下的答案表明,它是不可能注入的依赖阶目的。对此有何想法? http://stackoverflow.com/questions/31100534/can-we-use-google-guice-di-with-a-scala-object-instead-of-a-scala-class-in-play –

1

以上回答是正确的,但如果你不想使用ScalaGuice扩展,你可以做到以下几点:

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

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

而不是@提供您可以简单地在configure()中添加requestInjection(guideSpec) –