Scala : easily load an parse configuration files

There are a lot of ways to handle configuration files in a Scala program; my favorite one is to use TypeSafe's Config project

This library scans the CLASSPATH for a predefined set of configuration files in different formats

Using it it's pretty straightforward so let's get to it :

1.- Add your dependency to sbt
libraryDependencies += "com.typesafe" % "config" % "1.2.1"
2.- Loading the configuration file

//load the configuration file from the classpath
val conf = ConfigFactory.load

The convenience method ConfigFactory.load() loads the following (first-listed are higher priority):

  • system properties
  • application.conf (all resources on classpath with this name)
  • application.json (all resources on classpath with this name)
  • (all resources on classpath with this name)
  • reference.conf (all resources on classpath with this name)

The idea is that libraries and frameworks should ship with a reference.conf in their jar. Applications should provide an application.conf, or if they want to create multiple configurations in a single JVM, they could use ConfigFactory.load("myapp") to load their own myapp.conf. (Applications can provide a reference.conf also if they want, but you may not find it necessary to separate it from application.conf.)

3.- Reading the configuration file values
//retrieve configuration files values
val remoteIp = conf.getString("server.ip")
val remotePort = conf.getInt("server.port")

That's it for today; have fun!

Popular posts from this blog

Multi-hop ssh tunnel - howto : Creating a SSH tunnel with port forwarding between multiple hosts

Spring boot and spring data jpa tutorial - A sample application using spring 4.0 spring boot and JPA (part 2/2)

MongoDB spring data $elemMatch in field projection