How to access Play Framework 2.4 guice Injector in application?

前端 未结 5 1487
予麋鹿
予麋鹿 2021-01-11 21:57

I want to use the getInstance method of the Guice Injector class in Play Framework 2.4, how can I access it?

I have used the Guice Fa

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-11 22:13

    There are many ways. I use this one.

    Edit: This is relevant for Play versions which are <= 2.4:

    Play.maybeApplication.map(_.injector.instanceOf[MyProdClass]).getOrElse(new MyDevClass)
    

    or

    Play.current.injector.instanceOf[MyClass]
    

    For versions which are >= 2.5:

    import play.api.inject.Injector
    import javax.inject.Inject
    
    class MyService @Inject() (injector: Injector) ={
        val myClassInstance = injector.instanceOf[MyClass]
        //do stuff
    }
    

提交回复
热议问题