How to access Play Framework 2.4 guice Injector in application?

前端 未结 5 1488
予麋鹿
予麋鹿 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 21:59

    Apart from the other Play 2.5.x solutions, there may be a situation in which you want to get the Injector in an object without using injection. For example when you're using a Scala singleton, for which @inject probably doesn't work.

    In that case, you can use this:

    @Singleton
    class GlobalContext @Inject()(injector: Injector) {
      GlobalContext.injector = injector
    }
    
    object GlobalContext {
      private var injector: Injector = null  
    }
    

    With a Guice module to set the singleton to eager, otherwise it won't be initialized automatically:

    // Module.scala
    class Module extends AbstractModule {
      override def configure() = {
        // ...
    
        // Eager initialize Context singleton
        bind(classOf[GlobalContext]).asEagerSingleton()
      }
    }
    

提交回复
热议问题