Documentation

You are viewing the documentation for the 2.8.20 release in the 2.8.x series of releases. The latest stable release series is 3.0.x.

§The Scala Configuration API

Play uses the Typesafe config library, but Play also provides a nice Scala wrapper called Configuration with more advanced Scala features. If you’re not familiar with Typesafe config, you may also want to read the documentation on configuration file syntax and features.

§Accessing the configuration

Typically, you’ll obtain a Configuration object through Dependency Injection, or simply by passing an instance of Configuration to your component:

class MyController @Inject() (config: Configuration, c: ControllerComponents) extends AbstractController(c) {
  def getFoo = Action {
    Ok(config.get[String]("foo"))
  }
}

The get method is the most common one you’ll use. This is used to get a single value at a path in the configuration file.


// foo = bar config.get[String]("foo") // bar = 8 config.get[Int]("bar") // baz = true config.get[Boolean]("baz") // listOfFoos = ["bar", "baz"] config.get[Seq[String]]("listOfFoos")

It accepts an implicit ConfigLoader, but for most common types like String, Int, and even Seq[String], there are already loaders defined that do what you’d expect.

Configuration also supports validating against a set of valid values:

config.getAndValidate[String]("foo", Set("bar", "baz"))

§ConfigLoader

By defining your own ConfigLoader, you can easily convert configuration into a custom type. This is used extensively in Play internally, and is a great way to bring more type safety to your use of configuration. For example:

case class AppConfig(title: String, baseUri: URI)
object AppConfig {
  implicit val configLoader: ConfigLoader[AppConfig] = new ConfigLoader[AppConfig] {
    def load(rootConfig: Config, path: String): AppConfig = {
      val config = rootConfig.getConfig(path)
      AppConfig(
        title = config.getString("title"),
        baseUri = new URI(config.getString("baseUri"))
      )
    }
  }
}

Then you can use config.get as we did above:

// app.config = {
//   title = "My App
//   baseUri = "https://example.com/"
// }
config.get[AppConfig]("app.config")

§Optional configuration keys

Play’s Configuration supports getting optional configuration keys using the getOptional[A] method. It works just like get[A] but will return None if the key does not exist. Instead of using this method, we recommend setting optional keys to null in your configuration file and using get[Option[A]]. But we provide this method for convenience in case you need to interface with libraries that use configuration in a non-standard way.

Next: HTTP programming