PHpullh
학습 라이브러리/Kotlin/설정 파일 관리 (Properties)

KOTLIN · 파일/IO

설정 파일 관리 (Properties)

Properties 파일과 환경 변수를 조합하여 애플리케이션 설정을 관리합니다.

파일/IO중급configpropertiesenvironmentsettings

핵심 설명

Properties 파일과 환경 변수를 조합하여 애플리케이션 설정을 관리합니다.

Kotlin code

import java.util.Properties
import java.io.StringReader

class AppConfig {
    private val props = Properties()

    fun loadFromString(content: String) {
        props.load(StringReader(content))
    }

    fun get(key: String): String? =
        System.getenv(key.uppercase().replace(".", "_"))
            ?: props.getProperty(key)

    fun getOrDefault(key: String, default: String): String =
        get(key) ?: default

    fun getInt(key: String, default: Int): Int =
        get(key)?.toIntOrNull() ?: default

    fun getBoolean(key: String, default: Boolean): Boolean =
        get(key)?.toBooleanStrictOrNull() ?: default

    fun getAll(): Map<String, String> =
        props.entries.associate { it.key.toString() to it.value.toString() }
}

fun main() {
    val configContent = """
        app.name=MyKotlinApp
        app.port=8080
        app.debug=true
        db.url=jdbc:postgresql://localhost/mydb
        db.pool.size=10
    """.trimIndent()

    val config = AppConfig()
    config.loadFromString(configContent)

    println("앱: ${config.get("app.name")}")
    println("포트: ${config.getInt("app.port", 3000)}")
    println("디버그: ${config.getBoolean("app.debug", false)}")
    println("DB: ${config.get("db.url")}")
    println("전체: ${config.getAll()}")
}

학습 팁

환경 변수를 Properties보다 우선시하면 배포 환경별 설정을 코드 변경 없이 적용할 수 있습니다(12-Factor App 원칙).

주의할 점

설정 파일에 비밀번호나 API 키를 직접 넣지 마세요. 환경 변수나 시크릿 매니저를 사용하고, .gitignore에 설정 파일을 추가하세요.

자주 묻는 질문

설정 파일 관리 (Properties)란 무엇인가요?

Properties 파일과 환경 변수를 조합하여 애플리케이션 설정을 관리합니다.

설정 파일 관리 (Properties) 학습 시 주의할 점은 무엇인가요?

설정 파일에 비밀번호나 API 키를 직접 넣지 마세요. 환경 변수나 시크릿 매니저를 사용하고, .gitignore에 설정 파일을 추가하세요.