简体   繁体   中英

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

Another way to do is

import com.typesafe.config.ConfigFactory
val restConfig = ConfigFactory.load("rest.conf") //your conf file
val pageSize = restConfig.getInt("pagesize") //the value you want from conf file

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM