Getting started with SparkJava

Let’s start with a Spark web application & Koin

About

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

Let’s go 👍

Get the code

Checkout the project directly on Github or download the zip file

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:1.0.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) : SparkController{
    init {
        get("/hello") {
            service.sayHello()
        }
    }
}

Declare your dependencies

Let’s assemble our components with a Koin module:

val helloAppModule = module {
    single<HelloService> { HelloServiceImpl(get()) } // get() Will resolve HelloRepository
    single<HelloRepository> { HelloRepositoryImpl() }
    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))
}

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

What’s Next?

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

Also other getting started project: