Search code examples
ktorkoin

How do I use custom configuration in Ktor?


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!


Solution

  • 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!