Search code examples
scaladependency-injectionplayframeworkguicetypesafe-config

How to inject correctly the play.api.Configuration inside an object in play framework2.5?


I am upgrading to play framework 2.5, I have objects that are very hard to turn them to classes in order to use dependency injection, so I used this method instead:

object test {
@Inject var config: Configuration = _
def portNumber = config.getInt("server.port")
}

However on runTime i got null pointer exception, the old code used to be like this :

object test {
def portNumber = Play.configuration.getInt("server.port")
}

but it is deperecated and I must change it with DI. and another question on the fly is it possible to the same if I have got a trait instead of an object


Solution

  • You could set the configuration in a Singleton, like:

    @Singleton
    class ConfigForTest @Inject()(config: Configuration) {
      test.config = config
    }
    

    And set from here config in the test Object.

    So your test object looks like this:

    object test {
       var config: Configuration = _
       def portNumber = config.getInt("server.port")
    }
    

    Don't forget to initialise the Singleton in your Module:

    class Module
      extends AbstractModule {
    
      @Override()
      override def configure(): Unit = {
    
        bind(classOf[ConfigForTest])
          .asEagerSingleton()
    ...
    

    Or as Shweta shows, do it without any Injection. As you have a Play app, this would be enough:

    import com.typesafe.config.ConfigFactory
    
    object test {
       val portNumber = ConfigFactory.load().getInt("server.port")
    }
    

    This takes application.conf direct from the Classpath.