2012-12-09 26 views

Trả lời

16

Một số nghiên cứu trên Google (xem this post) tiết lộ rằng bạn có thể thực hiện điều này như sau (mã sau đây là một thử nghiệm ScalaTest đơn vị):

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 
} 

này giả định bạn đang sử dụng scala-guiceScalaTest .

+0

câu trả lời trong bài viết dưới đây cho thấy nó không thể bơm phụ thuộc vào scala vật. bất kỳ ý tưởng về điều này? http://stackoverflow.com/questions/31100534/can-we-use-google-guice-di-with-a-scala-object-instead-of-a-scala-class-in-play –

1

Câu trả lời trên là chính xác, nhưng nếu bạn không muốn sử dụng ScalaGuice Extensions, bạn có thể làm như sau:

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

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

Thay vì @ Cung cấp cho bạn có thể chỉ cần thêm requestInjection (guideSpec) trong cấu hình() –

Các vấn đề liên quan