Estimate project
← All posts

Getting to Know Ktor from a Spring Boot Perspective. Part 1

This article targets developers who know Spring Boot and want to get into Ktor by building on what they already know. Comparing core concepts such as application setup, routing, and dependency injection, we will see how Ktor works internally and how its design fits Kotlin's idioms.

13 min read
Spring BootKotlinKtorKotlinServerSide

When you move from Java to Kotlin, you may start looking into frameworks built natively for Kotlin. Thanks to Kotlin’s excellent interoperability, using your existing Java tools is perfectly fine, but you may also want to try something new that makes full use of what Kotlin offers.

For web application development, you can choose between staying with the proven Spring Boot, which works smoothly with Kotlin, or jumping into Ktor, a framework designed from the start around Kotlin’s distinctive features and idioms.

Both frameworks set out to make web development simpler, yet in certain respects their philosophies and approaches differ. Spring Boot offers a robust, opinionated toolkit meant for applications of any size, whereas Ktor is a lightweight, flexible framework built for Kotlin with developer experience in mind.

This article targets developers who know Spring Boot and want to get into Ktor by building on what they already know. Comparing core concepts such as application setup, routing, and dependency injection, we will see how Ktor works internally and how its design fits Kotlin’s idioms. We will also look at where the two differ and where they are alike, so you can get productive fast without being overwhelmed.

Note: Because the topic is so broad, I split the article into two parts. The first goes into detail on Application Setup, Server Engines, Configuration, and Dependency Injection. The second covers HTTP Request Handling and exception Handling, HTTP Clients, and Testing.

If you would like to learn Ktor by relating it to what you already know, this article is meant for you. Let’s get started and see how Ktor brings Kotlin’s functional style to web development.

Setting up an application

One of the first challenges developers face when building web apps is creating the project and getting the application running with the configuration it needs. That covers starting the underlying servlet engine, configuring dependencies, and defining application modules. Spring Boot and Ktor both let you get going fast, but they go about it in very different ways.

Spring boot

Spring Boot is guided by the “convention over configuration” principle, which keeps the boilerplate required to run an application to a minimum. A typical Spring Boot application begins with an entry point class marked with @SpringBootApplication:

@SpringBootApplication 
class MyApp 

fun main(args: Array<String>) { 
    runApplication<MyApp>(*args) 
}

That one annotation turns on the following features:

  • Designates the class as a source of bean definitions
  • Turns on Spring Boot’s auto-configuration mechanism
  • Scans the application’s package hierarchy for components

The magic of Spring Boot comes from auto-configuration, which sets up beans automatically depending on what dependencies are on your classpath. As a result, you usually do not need any implicit configuration – you just add the right dependencies to the project.

To kick off a new project with the right dependencies, you can use a dedicated generator web app that makes this easy: start.spring.io. It produces a ready-to-use project based on the Spring Boot version you target, your chosen language, build tool, and dependencies.

Ktor

Ktor, on the other hand, takes a more explicit and modular route, relying on Kotlin’s DSL capabilities. Here is a simple Ktor application:

fun main() { 
  embeddedServer(Netty, port = 8080) { 
    routing { 
      get("/hello") { 
        call.respondText("Hello, World!") 
      } 
    } 
  }.start(wait = true) 
}

Ktor’s philosophy is “no magic”: the application flow is more transparent, but you have to configure more explicitly, using Kotlin’s functional features with type-safe builders. Everything is opt-in and has to be declared explicitly when you need it. Annotations and reflection are not used.

When you want to add functionality to your application – for example defining routes and exposing endpoints, enabling dependency injection, or using an HTTP client – you usually add the relevant dependencies and install the matching plugin. A plugin is a modular component that extends what the Ktor server and client can do. To enable routing, for instance, you add the io.ktor:ktor-server-core dependency and install the Routing plugin.

Just like Spring Boot, Ktor offers an online application generator: start.ktor.io, which makes picking the right dependencies and plugins easier. Besides the basics (target Ktor version, build system, engine, etc.), you have to select the plugins your application will use.

Server engines

In web applications, the server engine is the base of the application’s runtime environment. Spring Boot and Ktor handle server engine configuration differently. Spring Boot hides most of the server implementation details, while Ktor makes developers explicitly decide which engine runs their application.

Spring Boot

Spring Boot uses Tomcat as its default embedded server, but you can easily swap it for Jetty or Undertow without touching application code. To use Jetty, for instance, all you need is the appropriate dependency.

dependencies { 
  implementation("org.springframework.boot:spring-boot-starter-web") 

  // To switch to Jetty    
  implementation("org.springframework.boot:spring-boot-starter-jetty")    
  exclude("org.springframework.boot", "spring-boot-starter-tomcat") 
}

The server engine is configured through properties in your application.properties or application.yml file. Based on those properties, the framework configures the embedded server automatically, so you can adjust things like port numbers, thread pools, and SSL without writing any code.

Ktor

Ktor ships with several server engines, including Tomcat, Netty, and Jetty. It also has an engine called CIO (Coroutine I/O) – Ktor’s own Kotlin-specific engine, designed from scratch around coroutines for very efficient, non-blocking I/O, which makes it a great fit for applications built on Kotlin’s concurrency model.

To run an application on a given server engine, you add the corresponding dependency.

dependencies {
    implementation("io.ktor:ktor-server-core:$ktor_version")
    implementation("io.ktor:ktor-server-netty:$ktor_version") // Using Netty

    // For other engines:
    // implementation("io.ktor:ktor-server-jetty:$ktor_version")
    // implementation("io.ktor:ktor-server-tomcat:$ktor_version")
    // implementation("io.ktor:ktor-server-cio:$ktor_version")
}

There are two ways to configure and start the server in Ktor. With embeddedServer, you configure and launch the server engine programmatically in code, which gives you fine-grained control over its setup and makes dynamic configuration possible.

fun main() {
    embeddedServer(Netty, port = 8080) {
        routing {
            get("/hello") {
                call.respondText("Hello, world!")
            }
       }
    }.start(wait = true)
}

You can supply configuration specific to the underlying server engine. Here is an example for the Netty server:

fun main(args: Array<String>) {
    embeddedServer(Netty, configure = {
        shutdownGracePeriod = 1000
        shutdownTimeout = 2000
    }) {
        routing {
            get("/hello") {
                call.respondText("Hello, world!")
            }
        }
    }.start(wait = true)
}

EngineMain, by contrast, is more declarative: the server is configured in an external application.conf (or yaml) file and started through a main function supplied by Ktor. This cleanly separates code from configuration, which is very helpful in environments where deployment parameters change.

fun main(args: Array<String>): Unit = EngineMain.main(args)

fun Application.module() {
    routing {
        get("/hello") {
            call.respondText("Hello, world!")
        }
    }
}

With this setup, the engine configuration lives in a dedicated file – application.conf (or yaml):

ktor {
    deployment {
        port = 8080
      shutdownGracePeriod = 2000
        shutdownTimeout = 3000
    }
    application {
        modules = [ pl.rmaciak.ApplicationKt.module ]
    }
}

Application configuration

Any application we build needs configuration that can be tailored to the environment it runs in or to a particular tenant’s requirements. Spring Boot and Ktor take different approaches to managing configuration, environment-specific settings included. Let’s look at how each framework deals with application configuration.

Configuration files

Spring Boot

Spring Boot mainly uses two kinds of configuration files: application.yml and application.properties. You can keep all application configuration in them, custom properties included.

To read particular properties in code, you can use the @Value annotation.

@Component
class DatabaseProperties {
    @Value("\${spring.datasource.url}")
    lateinit var url: String

    @Value("\${spring.datasource.username}")
    lateinit var username: String
}

Another popular way to access application configuration is @ConfigurationProperties, which injects configuration values into class fields.

@ConfigurationProperties(prefix = "spring.datasource")
class DataSourceProperties {
    var url: String = ""
    var username: String = ""
}

Ktor

Ktor uses the HOCON (Human-Optimized Config Object Notation) format, which is more flexible and supports features such as including other files, substitutions, and multi-line strings. Below is a simple HOCON configuration file.

ktor {
    deployment {
        port = 8080
    }

    application {
        modules = [ pl.rmaciak.ApplicationKt.module ]
    }
}

database {
    url = "jdbc:postgresql://localhost:5432/myapp"
    username = "postgres"
}

logging {
    level = "INFO"
}

Ktor loads its configuration from application.conf (YAML configuration is supported as well) in the resources directory, from system properties, or from environment variables. In code, you read a configuration property through the environment field.

fun Application.module() {
    val databaseUrl = environment.config.property("database.url").getString()
    val databaseUsername = environment.config.property("database.username").getString()
}

Ktor has no built-in way to inject configuration properties into object fields (as @ConfigurationProperties does in Spring Boot), but a little code is enough to do it.

data class DatabaseConfig(
    val url: String,
    val username: String,
)

fun Application.configureDatabases() {
    val config = environment.config("database")
    val databaseConfig = DatabaseConfig(
        url = config.property("url").getString(),
        username = config.property("username").getString(),
    )
}

Environment specific configuration

Spring Boot

In Spring Boot, environment-specific configuration is usually handled with profiles, which let you supply separate configuration for each environment. You do this by creating application- .properties files, where is the profile name – typically the name of the environment. For instance, to keep DEV and PROD configuration apart, you would have two files, application-dev.properties and application-prod.properties, each with its own set of properties:

# application-dev.properties
server.port=8080
spring.datasource.url=jdbc:h2:mem:myapp

# application-prod.properties
server.port=80
spring.datasource.url=jdbc:postgresql://production-db:5432/myapp

A specific profile is activated by setting the spring.profiles.active property, either via a command line argument or an environment variable.

Ktor

Ktor offers no convention or mechanism for environment-specific configuration, but – as with other areas – you can easily get there explicitly by using HOCON’s inheritance and substitution features:

# application.conf

database { 
    url = "jdbc:h2:mem:devdb"
}

# For different environments, you can include environment-specific files
include "application-${?KTOR_ENV}.conf"
# application-prod.conf

database {
    url = "jdbc:postgresql://production-db:5432/proddb"
}

Here, the application determines the environment from the KTOR_ENV variable. When it is not set, the default configuration file (application.conf) is used. In production, KTOR_ENV should be set to “prod”, so that application-prod.conf with the production-specific configuration gets picked up.

Dependency injection

With dependency injection, components are given their dependencies (the objects they need to work) instead of creating them, which encourages loose coupling and makes testing easier. Coming from Spring Boot, you might be surprised that Ktor has no IoC container out of the box. It favors explicitness by having you create components directly in code, or you can pick one of the plugins or frameworks that add DI capabilities to Ktor.

Spring Boot

Spring Boot sits on top of Spring’s Inversion of Control (IoC) container, which handles object creation and lifecycle and depends heavily on reflection and annotations. To declare a class as a bean (an object managed by IoC that can be injected into other objects), you use one of these annotations – @Component, @Service, @Repository, @Controller – depending on which layer the class belongs to. Several injection styles exist, but constructor injection is the recommended one.

For instance, to turn UserService into a bean and inject it into UserController, you mark it as a @Service and add it to the controller’s constructor. Spring then injects a UserService instance into UserController automatically.

@Service
class UserService(private val userRepository: UserRepository) {
    fun findUser(id: Long): User = userRepository.findById(id).orElseThrow()
}

@RestController
@RequestMapping("/api/users")
class UserController(private val userService: UserService) {
    @GetMapping("/{id}")
    fun getUser(@PathVariable id: Long): User = userService.findUser(id)
}

Ktor

As noted before, Ktor has no built-in dependency injection. It promotes functional programming instead, through function composition, DSLs, and creating objects on demand. One option with Ktor is to drop DI entirely and define dependencies explicitly and programmatically. That works especially well when all you need from inversion of control is managing singletons – Kotlin does not need a framework for that. Declaring an object is enough to guarantee a single instance of a class.

object UserService {

    fun createUser() {
       //... some logic here
    }
}

This approach has its limits, though, because objects cannot declare dependencies via a constructor. So in practice you usually still need a DI framework. Fortunately, Ktor integrates easily with a range of DI frameworks:

  • Koin – a pragmatic, lightweight DI framework written purely in Kotlin, using functional resolution without proxies or reflection.
  • Kodein – a Kotlin-native dependency retrieval container focused on type safety and readability while staying small, a good fit for multiplatform projects.
  • Dagger – a compile-time dependency injection framework that generates code to guarantee type safety; it performs very well but is harder to learn and needs more verbose configuration.
  • Guice – Google’s mature Java-based DI framework offering runtime flexibility and dynamic binding, although it is heavier than Kotlin-specific options when combined with Ktor.

Here, I will show how to enable dependency injection in Ktor with Koin.

Using Koin with Ktor for dependency injection

To bring Koin into your Ktor application, add the appropriate dependencies and install the Koin plugin:

build.gradle.kts

dependencies { 
    implementation("io.insert-koin:koin-ktor:$koin_version") 

    // Optional for logging with SLF4J
    implementation("io.insert-koin:koin-logger-slf4j:$koin_version")  
}
fun Application.main() {
    install(Koin) {
        slf4jLogger() // Optional for logging with SLF4J
        modules(appModule) // Enabling Koin module called appModule
    }
}

Koin is built around modules – containers in which Koin dependencies are defined. Depending on what you need, you declare all your beans in one or several modules.

Koin comes with fewer predefined bean scopes than Spring Boot:

  • Single – one instance for the whole lifetime of the container (the equivalent of a Singleton in Spring Boot)
  • Factory – a fresh instance every time it is requested
  • Scoped – an instance bound to the lifecycle of a scope defined by the user

Even though Koin has fewer built-in scopes than Spring Boot, its scoped definition is very flexible. You can define your own scopes, which makes Koin more powerful and adaptable in some use cases.

A few examples of bean definitions in Koin:

val appModule = module {
    // 1. Singleton scope - one instance for the whole application, by deafault 
    lazy initialized 
    single<UserRepository> { UserRepositoryImpl() }

    // 2. Factory scope - creates a new instance each time it's requested
    factory { UserRepositoryImpl() }

    // 3. Multiple beans with named qualifiers
    single<PaymentGateway>(named("stripe")) { StripePaymentGateway() }
    single<PaymentGateway>(named("paypal")) { PaypalPaymentGateway() }

    // 4. Creating a bean with constructor parameters
    single { DatabaseConnection(get(), get<DatabaseConfig>().url) }

    // 5. Lazy singleton - only created when first accessed
    single(createdAtStart = false) { ExpensiveResourceManager() }

    // 6. Eager singleton - created at Koin startup
    single(createdAtStart = true) { SystemInitializer() }
}

Beans can be injected into your application in the following ways:

fun Application.configureRouting() {
    // 1. Property delegate injection
    val userRepository: UserRepository by inject()

    // 2. Direct retrieval from KoinComponent resolved by property type
    val userRepository: UserRepository = get()

    // 3. Direct retrieval from KoinComponent resolved by name
    val userRepository = get<UserRepository>(named("fakeUserRepository"))

    // 4. Lazy injection
    val lazyUserRepository: Lazy<UserRepository> by inject()

    // 5. Injecting with parameters
    val userRepository = get<UserRepository> { parametersOf("user123") }
}

Part 1 summary

This part aimed to give an overview of the Ktor framework and its features, and to relate them to concepts you know from Spring Boot so that learning it is easier. Here is a recap of the aspects described and compared:

Application Setup

  • Spring Boot: Relies on annotations together with auto-configuration and component scanning
  • Ktor: Takes an explicit, modular approach based on Kotlin’s DSL, without reflection or annotations

Server Engines

  • Spring Boot: Uses Tomcat by default and can easily switch to Jetty/Undertow through dependencies
  • Ktor: Offers several engines, including its own Coroutine I/O (CIO) engine, configured programmatically or declaratively

Configuration

  • Spring Boot: Relies on YAML/properties files with annotation-based injection and profiles
  • Ktor: Relies on YAML or HOCON, with direct property access and inheritance for environment-specific configs (HOCON only)

Dependency Injection

  • Spring Boot: Built-in IoC container driven by annotations
  • Ktor: No built-in DI; you can use Kotlin objects or third-party solutions (Koin, Kodein, etc.)

As this first part of Learning Ktor Through a Spring Boot Lens comes to an end, I hope it has given you a solid basis for seeing how Ktor’s core features correspond to familiar Spring Boot concepts. It is a step toward adopting Kotlin-native solutions while making use of what you already know.