2012-12-09 13 views
17

스칼라에서 Guice을 사용하여 스칼라 object을 삽입 할 수 있습니까?Guice가 스칼라 객체를 삽입 할 수 있습니까?

예를 들어 다음 객체에 s에 삽입 할 수 있습니까?

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을 사용하고 있습니다 :

object GuiceSpec { 
    @Inject 
    val s: String = null 

    def get() = s 
} 

답변

16
구글 ( this post 참조) 일부 연구는 다음과 같이이 작업을 수행 할 수 있음을 밝혀

(다음 코드는 ScalaTest 단위 테스트입니다) .

+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)을 간단히 추가 할 수 있습니다. –

관련 문제