Getting started with SparkJava

Let’s start with a Spark web application & Koin

SparkJava has now its Kotlin declination, and continue to assert its ambition for developing webapps in a smart & simple way.

Let’s go with the following Spark components to chain : a Controller, a Service and a Repository. All of those components assembled behind Spark with Koin.

Controller (http) -> Service (business) -> Repository (data)
  • a Controller to handle http route and return result from the service
  • a Service to handle business and take data from repository
  • a Repository to provide data

All sources are available in the Koin’s github repository

Let’s go 👍

Gradle Setup

First, add the Koin dependency like below:

// Add Jcenter to your repositories if needed
repositories {
    jcenter()    
}
dependencies {
    // Koin for Kotlin apps
    compile 'org.koin:koin-spark:0.9.2'
}

Service & Repository

Let’s write our Service, a component that will ask Repository for data:

interface HelloService {
    fun sayHello(): String
}

class HelloServiceImpl(val helloRepository: HelloRepository) : HelloService {
    override fun sayHello() = "Hello ${helloRepository.getHello()} !"
}

and our Repository, which provide data:

interface HelloRepository {
    fun getHello(): String
}

class HelloRepositoryImpl : HelloRepository {
    override fun getHello(): String = "Spark & Koin"
}

Finally, we need an HTTP Controller to create the HTTP Route

class HelloController(val service: HelloService){
    init {
        get("/hello") {
            service.sayHello()
        }
    }
}

Declare your dependencies

Let’s assemble our components with a Koin module:

val helloAppModule = applicationContext {
    bean { HelloServiceImpl(get()) as HelloService } // get() Will resolve HelloRepository
    bean { HelloRepositoryImpl() as HelloRepository }
    controller { HelloController(get()) } // get() Will resolve HelloService
}

Start and Inject

Finally, let’s start Koin:

fun main(vararg args: String) {
    // Start Spark server & Koin with given modules
    start(modules = listOf(helloAppModule)) {
        // will run HelloController
        runControllers()
    }
}

That’s it! You’re ready to go.

What’s Next?

You have finished this starting tutorial. Below are some topics for further reading:

General Topics

Developer Guide

Soon…