在Scala中,我可以使用Guice來注入Scala object
s嗎?Can Guice可以注入Scala對象
例如,我可以在s
注入以下對象嗎?
object GuiceSpec {
@Inject
val s: String = null
def get() = s
}
在Scala中,我可以使用Guice來注入Scala object
s嗎?Can Guice可以注入Scala對象
例如,我可以在s
注入以下對象嗎?
object GuiceSpec {
@Inject
val s: String = null
def get() = s
}
在谷歌(見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 。
以上回答是正確的,但如果你不想使用ScalaGuice
擴展,你可以做到以下幾點:
val injector = Guice.createInjector(new ScalaModule() {
def configure() {
bind[String].toInstance("foo")
}
@Provides
def guiceSpecProvider: GuiceSpec.type = GuiceSpec
})
而不是@提供您可以簡單地在configure()中添加requestInjection(guideSpec) –
在後下的答案表明,它是不可能注入的依賴階目的。對此有何想法? http://stackoverflow.com/questions/31100534/can-we-use-google-guice-di-with-a-scala-object-instead-of-a-scala-class-in-play –