Push SparkJava to the next level with Koin

How to develop a modular & testable app with Spark, Koin & Kotlin? Let’s see how it’s easy in a few minutes ;)


Spark is a micro framework for creating web applications in Kotlin and Java 8 with minimal effort. The project has now its Kotlin declination, and continue to assert its ambition for developing webapps in a smart & simple way. This state of mind matches perfectly with the Koin’s philosophy: simplicity of writing and smart APIs.

In the simplest case of writing a Spark webapp, you can start directly with your HTTP route declaration with just get("/hello").

I would like to go beyond that case a bit simple, and try to make a more complete component 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

Sources are available in the Koin’s github repository. Let’s go 👍

A better start

Firstly, I will use an HTTP Controller. A Controller is just a component that help declare routing and allow bind our HTTP request with others components. The HelloController can be written like that:

Then, let’s use Spark with the following start function. It handles all Spark init and allows to run things into a lambda, before waiting for the end of server initialization:

You can check here how I provide this way of starting Spark. This can be easily reused for testing.

Service & Repository

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

and our Repository, which provides data:

Our Service and Repository are decoupled with interfaces. And each implementation can be injected by its constructor (injecting via constructor is the most recommended way of preparing dependency injection).

Assembling with Koin

Let’s declare our Koin module this way (version 0.7.1 of Koin):

Service and Repository will be managed by Koin. Let’s plug our service into our Controller:

HelloController is tagged with the KoinComponent interface to allow the usage of by inject(). This interface is needed when you can't create directly components with Koin, and must bind with a runtime or an SDK.

And finally, let’s start Koin:

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

Testing

Now, you have no excuse to not test your code. The github project provides several testing samples:

  • Test Controller with complete application
  • Test controller with mock service
  • Test service and repository
  • Check Koin configuration

Below a sample, about Controller with mocked Service:

And its simple module for providing mocks:

Wrapping up

Koin is your perfect companion to write applications with SparkKotlin. All sources are available in the Koin’s github repository. Go play with it! 😉