Skip to Content
Course content

243: Typesafe Config Library In Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've probably noticed that most professional Scala projects don't hardcode their settings. They use the Typesafe (now Lightbend) Config library. It's the industry standard for a reason—it handles HOCON (Human-Optimized Config Object Notation), which is basically JSON but without the annoying requirement for quotes and commas everywhere.

How do I actually load the config and pull out specific values?

The most common way to start is by calling ConfigFactory.load(). This looks for a file named application.conf on your classpath by default. I recommend treating your config as a read-only source of truth that you access at the very start of your application's lifecycle.

Let's say you're building a Payment Gateway integration. Your application.conf might look like this:

payment-gateway {
  api-key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
  timeout = 5000
  retry-attempts = 3
  endpoints {
    auth = "https://api.gateway.com/v1/auth"
    charge = "https://api.gateway.com/v1/charge"
  }
}

To get these values into your Scala code, you use the typed getters. Avoid using generic getAny calls; be explicit about what you expect.

import com.typesafe.config.ConfigFactory

val config = ConfigFactory.load()

val apiKey = config.getString("payment-gateway.api-key")
val timeout = config.getInt("payment-gateway.timeout")
val authUrl = config.getString("payment-gateway.endpoints.auth")

println(s"Connecting to $authUrl with timeout $timeout ms")

How does the layering and fallback system actually work?

This is where the library really shines. In a real-world project, you don't want to force your users to define every single setting. You want to provide sensible defaults that they can override if they need to.

The pattern is: reference.conf $\rightarrow$ application.conf $\rightarrow$ System Properties.

  • reference.conf: Put this in your library or module. It contains the "factory defaults."
  • application.conf: This is where the end-user (or you, in the main app) overrides specific values.
  • System Properties: You can override anything at runtime using -Dpayment-gateway.timeout=10000.

The library handles this merge automatically when you call ConfigFactory.load(). If a key isn't found in application.conf, it looks in reference.conf. I've found this incredibly useful for creating "profiles" (like dev vs prod) where 90% of the config stays the same, and you only override the database URL.

Is there a way to avoid passing the Config object around my whole app?

Please, for the love of your unit tests, do not pass the Config object into every single class in your system. If you do, your business logic becomes coupled to the config library, and your tests will require a dummy application.conf just to instantiate a class.

Instead, map the config into a simple Scala case class immediately upon startup. I call this the "Configuration Object" pattern. You do the "dirty work" of extracting strings and ints in one place, and then pass the typed case class where it's needed.

case class GatewayConfig(
  apiKey: String,
  timeout: Int,
  authUrl: String
)

object ConfigLoader {
  def loadGatewayConfig: GatewayConfig = {
    val conf = ConfigFactory.load().getConfig("payment-gateway")
    GatewayConfig(
      apiKey = conf.getString("api-key"),
      timeout = conf.getInt("timeout"),
      authUrl = conf.getString("endpoints.auth")
    )
  }
}

// In your main app:
val gatewaySettings = ConfigLoader.loadGatewayConfig()
val service = PaymentService(gatewaySettings) // Service only knows about GatewayConfig, not the library

It takes a few extra lines of code, but it makes your architecture much cleaner. You can now test PaymentService by just passing in GatewayConfig("test-key", 100, "http://localhost") without touching any files.




📋 Practical Task

Exercise: Building a Multi-Environment Database Connector Config

Your goal is to implement a configuration system for a database connector that supports default values and environment-specific overrides.

  1. Create a file named src/main/resources/reference.conf. Define a block called db with the following defaults:
    • host = "localhost"
    • port = 5432
    • pool-size = 10
  2. Create a file named src/main/resources/application.conf. In this file, override the host to "prod-db.cluster.internal" and the pool-size to 50. Leave the port alone so it falls back to the reference value.
  3. Create a Scala case class DatabaseSettings(host: String, port: Int, poolSize: Int).
  4. Write a DatabaseConfigLoader object with a method load() that:
    • Loads the configuration using ConfigFactory.load().
    • Extracts the values from the db path.
    • Returns an instance of DatabaseSettings.
  5. In a main method, load the settings and print them to verify that the host and pool-size are from application.conf, while the port is from reference.conf.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.