Can Guice inject Scala objects

前端 未结 2 1262
忘了有多久
忘了有多久 2021-01-01 13:22

In Scala, can I use Guice to inject Scala objects?

For example, can I inject into s in the following object?



        
相关标签:
2条回答
  • 2021-01-01 13:38

    The above answer is correct, but if you don't want to use ScalaGuice Extensions, you can do the following:

    val injector = Guice.createInjector(new ScalaModule() {
        def configure() {
          bind[String].toInstance("foo")
        }
    
        @Provides
        def guiceSpecProvider: GuiceSpec.type = GuiceSpec
      })
    
    0 讨论(0)
  • 2021-01-01 13:55

    Some research on Google revealed that you can accomplish this as follows (the code that follows is a ScalaTest unit test):

    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
      var s: String = null
    
      def get() = s
    }
    

    This assumes you are using scala-guice and ScalaTest.

    0 讨论(0)
提交回复
热议问题