How to use the Lightbend Config library in a Scala or Java application

If you want to use Lightbend Config configuration files in your Scala or Java application, here’s a quick example of how to configure and use Lightbend Config in your application. In this case I’m specifically using Scala and SBT.

Note that Lightbend used to be named Typesafe, so you’ll see references to typesafe in the code.

Back to top

Adding the Lightbend Config dependency

The first thing to do is to add the Lightbend Config library as a dependency to your application. Do that by adding this line to your SBT build.sbt file:

"com.typesafe" % "config" % "1.3.2"

Note that you add that to your libraryDependencies like this:

libraryDependencies ++= Seq(
    "mysql"        % "mysql-connector-java" % "5.1.46",
    "com.typesafe" % "config"               % "1.3.2"
)
Back to top

A Scala application that uses Lightbend Config

Next, here’s a little Scala application that uses a Lightbend Config configuration file:

import com.typesafe.config.{Config, ConfigFactory}

object ReadConfigurationFile extends App {

    val config: Config = ConfigFactory.load("my_app.conf")

    val driver = config.getString("jdbc.driver")
    val url = config.getString("jdbc.url")
    val username = config.getString("jdbc.username")
    val password = config.getString("jdbc.password")
   
    println(s"driver =   $driver")
    println(s"url =      $url")
    println(s"username = $username")
    println(s"password = $password")

}

Note that SBT expects this configuration file to be in your src/main/resources folder by default. If you want to put your configuration file somewhere else, I wrote another tutorial about How to manually specify the custom location of a Lightbend Config configuration file.

Back to top

The Lightbend Config configuration file

Finally, here’s a Lightbend Config configuration file I named my_app.conf that works with that application:

jdbc {
    driver  = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:8889/kbhr_geo"
    username = "root"
    password = "root"
}
Back to top

Discussion

If you know how to work with Scala and SBT, that code should work just fine out of the box. Note that if you get an error message like this when running your application:

No configuration setting found for key ...

it probably means:

  • Your Lightbend Config configuration file can’t be found
  • If you change any of the name of the configuration file parameters, it can also mean that the name in the configuration file doesn’t match the name in your Scala/Java source code

In summary, if you needed a little example of how to use the Lightbend Config configuration file library in your Scala/Java project, I hope this example is helpful.

Back to top

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.