We are working on making Koin friendly with more Kotlin projects, trying to make things easier for Kotlin developers.
After giving some help to Android developers, we are working with some web frameworks. SparkJava is a microframework for creating web applications, and we can give them a hand with bringing a new Koin module. Koin has been lastly released in 0.8.0, adding the new koin-spark module.
I propose to go a step further than my last article on Spark(push SparkJava to the next level) and use those new Koin features. We are still working with the following components chain:
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 the repository
- a Repository to provide data
The complete project sources can be found on GitHub: koin-samples@github.
Get the setup from https://insert-koin.io (Koin’s official website) for Gradle (don’t forget to add jcenter() repository):
Our first controller
Firstly, I will use an HTTP Controller. A Controller is just a class that helps declare routing and allow bind our HTTP request with others components.
Then, let’s use Spark with the following startSpark() function. It handles all Spark init and allows to run things into a lambda, before waiting for the end of server initialization:
The new Koin module koin-spark, provides this ability to start Spark server. This also can be easily reused for testing.
Writing our Service & Repository
Now, let’s write our Service, a component that will ask Repository for data:
Our Repository will provide data:
And finally, let’s update our controller to inject our service:
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). All our components are injected by constructors (no need of KoinComponent interface anymore).
Assembling components with Koin
Let’s declare our Koin module this way:
All the components are managed by Koin. Note that we have a special controller keyword, dedicated to declare our Spark controller.
That’s it! The runControllers() function is here to launch all declared Spark controllers. 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 complete application
- Test controller with mock service
- Test service and repository
- Check Koin configuration
Here is how you can test your controller (Spark server just run with the HelloController here):
Another sample of controller test, but with mocked service:
Koin can be a perfect companion to write applications with SparkKotlin. All sources are available in the Koin samples GitHub repository. Go play with it! 😉
And don’t miss our new website. Rendez-vous at insert-koin.ioGoogle+