Reputation: 7220
I'm digging the built-in configuration support, and want to use it (instead of just rolling my own alongside Ktor's), but I'm having a hard time figuring out how to do it in a clean way. I've got this, and it's working, but it's really ugly and I feel like there has to be a better way:
val myBatisConfig = MyBatisConfig(
environment.config.property("mybatis.url").getString(),
environment.config.property("mybatis.driver").getString(),
environment.config.property("mybatis.poolSize").getString().toInt())
installKoin(listOf(mybatisModule(myBatisConfig), appModule), logger = SLF4JLogger())
Thanks for any help!
Upvotes: 4
Views: 8594
Reputation: 3350
You could also try this solution:
class MyService(val url: String)
fun KoinApplication.loadMyKoins(environment: ApplicationEnvironment): KoinApplication {
val myFirstModule = module {
single { MyService(environment.config.property("mybatis.url").getString()) }
}
val mySecondModule = module {}
return modules(listOf(myFirstModule, mySecondModule))
}
fun Application.main() {
install(DefaultHeaders)
install(Koin) {
loadMyKoins(environment)
SLF4JLogger()
}
routing {
val service by inject<MyService>()
get("/") {
call.respond("Hello world! This is my service url: ${service.url}")
}
}
}
fun main(args: Array<String>) {
embeddedServer(Netty, commandLineEnvironment(args)).start()
}
Upvotes: 3
Reputation: 1697
Adding to the existing accepted answer. An implementation using ConfigFactory.load()
could look like this (Without libs):
object Config {
@KtorExperimentalAPI
val config = HoconApplicationConfig(ConfigFactory.load())
@KtorExperimentalAPI
fun getProperty(key: String): String? = config.propertyOrNull(key)?.getString()
@KtorExperimentalAPI
fun requireProperty(key: String): String = getProperty(key)
?: throw IllegalStateException("Missing property $key")
}
So, theconfig class would become:
val myBatisConfig = MyBatisConfig(
requireProperty("mybatis.url"),
requireProperty("mybatis.driver"),
requireProperty("mybatis.poolSize").toInt())
Upvotes: 6
Reputation: 7220
Okay, I think I have a good, clean way of doing this now. The trick is to not bother going through the framework itself. You can get your entire configuration, as these cool HOCON files, extremely easily:
val config = ConfigFactory.load()
And then you can walk the tree yourself and build your objects, or use a project called config4k
which will build your model classes for you. So, my setup above has added more configuration, but gotten much simpler and more maintainable:
installKoin(listOf(
mybatisModule(config.extract("mybatis")),
zendeskModule(config.extract("zendesk")),
appModule),
logger = SLF4JLogger())
Hope someone finds this useful!
Upvotes: 8