2012-12-09 10 views

答えて

16

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-guiceScalaTestを使用していることを前提と。

+0

以下の記事で答えが、Scalaでは依存関係を注入することはできません示唆オブジェクト。これについての任意のアイデア? 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)を追加するだけで、 –

関連する問題