Reputation: 111
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
Upvotes: 3
Views: 1959
Reputation: 14803
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.
Upvotes: 1
Reputation: 158
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
Upvotes: 4