Trong Scala, tôi có thể sử dụng Guice để tiêm Scala object
s không?Có thể Guice tiêm đối tượng Scala
Ví dụ: tôi có thể tiêm vào s
trong đối tượng sau không?
object GuiceSpec {
@Inject
val s: String = null
def get() = s
}
Trong Scala, tôi có thể sử dụng Guice để tiêm Scala object
s không?Có thể Guice tiêm đối tượng Scala
Ví dụ: tôi có thể tiêm vào s
trong đối tượng sau không?
object GuiceSpec {
@Inject
val s: String = null
def get() = s
}
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-guice và ScalaTest .
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
})
Thay vì @ Cung cấp cho bạn có thể chỉ cần thêm requestInjection (guideSpec) trong cấu hình() –
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 –