我使用 .properties 文件来遵循这个示例 github 项目 Kotlin-dev-proxy。
服务器读取名为app_environment 的环境变量并使用相应的资源文件。
示例代码:
DbConfig.kt
data class DbConfig(
val dbHost: String,
val dbUsername: String,
val dbPassword: String,
val dbName: String,
val dbPort: Int)
ServerSettings.kt
class ServerSettings(settings: String) {
val resources = Properties()
init {
val fileUrl: URL = resources.javaClass.getResource("/$settings.properties")
?: throw FileNotFoundException("$settings.properties file not found")
fileUrl.openStream().use { resources.load(it) }
}
fun printSettings() = resources.stringPropertyNames().forEach {
println("Property: $it has value: '${resources[it]}'")
}
fun getString(key: String): String = resources[key]!! as String
fun getInt(key: String): Int = (resources[key]!! as String).toInt()
}
DbConfig.kt
fun provideDbConfig(): DbConfig {
val settings = ServerSettings(System.getenv("app_environment"))
settings.printSettings()
return DbConfig(
dbHost = settings.getString("dbHost"),
dbUsername = settings.getString("dbUsername"),
dbPassword = settings.getString("dbPassword"),
dbName = settings.getString("dbName"),
dbPort = settings.getInt("dbPort")
)
}
resources/develop.properties
# Local Db values
dbHost=localhost
dbUsername=postgresusername
dbPassword=postgrespassword
dbName=mydbname
dbPort=5432
在 Amazon EBS 中部署时,转到软件配置并添加适合环境的环境变量(暂存/生产)。