Configuration files

suggest change

Modern Kotlin applications manage application behavior, database connections, and external service URLs using structured configuration files. Depending on the framework and architecture, common formats include Properties, HOCON, YAML, and JSON, frequently mapped directly to strongly typed Kotlin data classes.


Standard Java Properties Files

Java .properties files are supported out of the box by the JVM without requiring any third-party dependencies.

# src/main/resources/config.properties
app.name=KotlinOrderService
app.port=8080
database.pool.size=10
feature.new-checkout=true

Loading from Resources

import java.io.InputStream
import java.util.Properties

object AppConfig {
    private val props = Properties()

    init {
        val stream: InputStream? = object {}.javaClass.getResourceAsStream("/config.properties")
        checkNotNull(stream) { "config.properties not found on classpath" }
        stream.use { props.load(it) }
    }

    val appName: String get() = props.getProperty("app.name", "DefaultApp")
    val port: Int get() = props.getProperty("app.port", "8080").toInt()
    val poolSize: Int get() = props.getProperty("database.pool.size", "5").toInt()
    val isNewCheckoutEnabled: Boolean get() = props.getProperty("feature.new-checkout", "false").toBoolean()
}

fun main() {
    println("Starting ${AppConfig.appName} on port ${AppConfig.port}")
    println("Checkout feature flag: ${AppConfig.isNewCheckoutEnabled}")
}

HOCON and YAML in Ktor

Ktor uses HOCON (.conf) or YAML (.yaml) files located in src/main/resources for application configuration.

Example application.yaml

ktor:
  deployment:
    port: 8080
    host: 0.0.0.0
  application:
    modules:
      - com.example.ApplicationKt.module

database:
  driver: "org.postgresql.Driver"
  url: "jdbc:postgresql://localhost:5432/orders"
  maxPoolSize: 20

Reading Configuration in Ktor Code

import io.ktor.server.application.*
import io.ktor.server.config.*

fun Application.module() {
    // Reading specific properties
    val dbDriver = environment.config.property("database.driver").getString()
    val dbUrl = environment.config.property("database.url").getString()
    val maxPoolSize = environment.config.propertyOrNull("database.maxPoolSize")?.getString()?.toInt() ?: 10

    log.info("Connecting to $dbUrl with pool size $maxPoolSize using $dbDriver")
}

Strongly Typed Configuration with Hoplite

Hoplite is a Kotlin library that parses YAML, JSON, TOML, HOCON, and properties files directly into immutable Kotlin data classes with validation and environment variable overrides.

Dependencies (Gradle)

implementation("com.sksamuel.hoplite:hoplite-core:3.0.4")
implementation("com.sksamuel.hoplite:hoplite-yaml:3.0.4")

Defining Types and Loading Configuration

import com.sksamuel.hoplite.ConfigLoaderBuilder
import com.sksamuel.hoplite.addFileSource
import com.sksamuel.hoplite.addResourceSource
import java.io.File

data class DatabaseConfig(
    val url: String,
    val poolSize: Int = 10,
    val timeoutSeconds: Long = 30
)

data class ServerConfig(
    val port: Int,
    val host: String = "0.0.0.0"
)

data class ApplicationConfiguration(
    val server: ServerConfig,
    val database: DatabaseConfig,
    val allowedOrigins: List<String>
)

fun loadConfiguration(): ApplicationConfiguration {
    // Sources added first take precedence over sources added later
    return ConfigLoaderBuilder.default() // includes environment variables (e.g. SERVER_PORT=9000) as the top source
        // 1. Optional external file override (e.g. in /etc/myapp/config.yaml)
        .addFileSource(File("/etc/myapp/config.yaml"), optional = true)
        // 2. Fallback default file from resources
        .addResourceSource("/application.yaml")
        .build()
        .loadConfigOrThrow<ApplicationConfiguration>()
}

fun main() {
    val config = loadConfiguration()
    println("Config loaded successfully! Port: ${config.server.port}, DB: ${config.database.url}")
}

JSON Configuration with kotlinx.serialization

When using JSON for configuration files:

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import java.io.File

@Serializable
data class ServiceConfig(
    val serviceName: String,
    val port: Int,
    val debug: Boolean = false,
    val endpoints: Map<String, String> = emptyMap()
)

fun loadJsonConfig(file: File): ServiceConfig {
    val jsonParser = Json {
        ignoreUnknownKeys = true
        isLenient = true
    }
    return jsonParser.decodeFromString<ServiceConfig>(file.readText())
}

Configuration Architecture Best Practices

  1. Hierarchy and Cascading: Load configuration hierarchically: built-in defaults (application.yaml) $\to$ environment-specific file (application-prod.yaml) $\to$ system environment variables.
  2. Fail Fast on Missing Keys: Validate and parse all configuration during application startup. If a required database URL is missing, crash immediately before opening network listeners.
  3. Keep Config Objects Immutable: Declare all configuration properties as val within data class containers. Never allow mutable configuration states at runtime.
  4. Segregate Secrets: Store non-sensitive defaults (timeouts, worker pool sizes) in git-tracked configuration files, but inject secrets (API tokens, private keys, passwords) via environment variables or secret vaults.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents