Scalaでは、Guiceを使ってScala object
を挿入できますか?GuiceはScalaオブジェクトを挿入できます
たとえば、次のオブジェクトのs
に注入できますか?
object GuiceSpec {
@Inject
val s: String = null
def get() = s
}
Scalaでは、Guiceを使ってScala object
を挿入できますか?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を使用していることを前提と。
上記の答えが正しいですが、ScalaGuice
拡張機能を使用したくない場合は、次の操作を実行できます。
val injector = Guice.createInjector(new ScalaModule() {
def configure() {
bind[String].toInstance("foo")
}
@Provides
def guiceSpecProvider: GuiceSpec.type = GuiceSpec
})
@ configure()でrequestInjection(guideSpec)を追加するだけで、 –
以下の記事で答えが、Scalaでは依存関係を注入することはできません示唆オブジェクト。これについての任意のアイデア? http://stackoverflow.com/questions/31100534/can-we-use-google-guice-di-with-a-scala-object-instead-of-a-scala-class-in-play –