Reading Time: 2 minutes

There are several ways of reading configuration files in Scala including the java properties way with the deprecated Configgy and quite some more. One way which is easy and comes in handy is with the Typesafe Config project which is also used in Akka.

Let us quickly see how to set it up,

You would need to include the following dependency in your build.sbt or Build.scala.

libraryDependencies += "org.skife.com.typesafe.config" % "typesafe-config" % "0.3.0"

Once you have this, setting up the logger is straight forward. The snippet in our case is

/** Loads all key/value pairs from the application configuration file. */ var conf = ConfigFactory.load /** Seed locations for which URLs are valid, example ca, nj etc*/ lazy val seedLocations = conf.getString("supplier.yelp.seed.locations")

The ConfigFactory.load by default looks for the following files in order

*system properties

*application.conf (all resources on classpath with this name)

*application.json (all resources on classpath with this name)

*application.properties (all resources on classpath with this name)

*reference.conf (all resources on classpath with this name)

You could also load it with a different file using ConfigFactory.load(file-name), like when you would want to execute tests.

and the configuration file would look like this

# these are the valid URLs for a given supplier site supplier { yelp { seed.locations="ca|nj" seed.pages="http://www.yelp.com/functions/(seedLocations)+[//]+$" } help { seed.locations="pn|tx" seed.pages="http://www.yelp.com/functions/(seedLocations)+[//]+$" } }

As you would notice, we can access the subsections. Let us see it through a test

import com.typesafe.config.ConfigFactory import org.junit.runner.RunWith import org.scalatest.FunSuite import org.scalatest.junit.JUnitRunner /** * Checks that properties mentioned as a part of application.conf * are read properly. */ @RunWith(classOf[JUnitRunner]) class ConfigurationTester extends FunSuite { test("check that supplier values are being read properly") { val conf = ConfigFactory.load("test-application.conf") assert(true === conf.hasPath("supplier.yelp.seed.pages")) assert(true === conf.hasPath("supplier.yelp.seed.locations")) assert(false === conf.hasPath("supplier.yelp.event.list.pages")) assert(true === conf.hasPath("supplier.help.seed.pages")) assert(true === conf.hasPath("supplier.help.seed.locations")) } }

More details on the project here