Push SparkJava to the Next Level With Koin
A developer provides a tutorial on how to create a complete component chain for a web app using Koin, a Kotlin declination.
Join the DZone community and get the full member experience.Join For Free
SparkJava has now its Kotlin declination and continues to assert its ambition for developing web apps in a smart and simple way. This state of mind matches perfectly with Koin’s philosophy: simplicity of writing and smart APIs.
In the simplest case of writing a Spark web app, you can start directly with your HTTP route declaration with just
I would like to go beyond that case, as it is a bit simple, and try to make a more complete component chain (a Controller, a Service, and a Repository) with all of those components assembled behind Spark with Koin.
Controller (http) -> Service (business) -> Repository (data)
- A Controller to handle HTTP routes and return results from the service.
- A Service to handle business and take data from the 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 helps declare routing and allows us to bind our HTTP request with others components. The
HelloController can be written like so:
Then, let’s use Spark with the following
start function. It handles all Spark inits and allows us to run things into a lambda, before waiting for the end of the server initialization:
You can check here to see how I provide this way of starting Spark. This can be easily reused for testing.
Service and Repository
Now, let’s write our Service, a component that will ask the 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 a 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 directly create 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.
Now, you have no excuse to not test your code. The GitHub project provides several testing samples:
- Test Controller with a complete application.
- Test controller with a mock service.
- Test the service and repository.
- Check Koin configuration.
Below is a sample of a Controller with a mocked Service:
And its simple module for providing mocks:
Koin is your perfect companion to write applications with SparkKotlin. All sources are available in Koin’s GitHub repository. Go play with it!
Opinions expressed by DZone contributors are their own.