DEV Community

Cover image for Less boilerplate: Crnk with Kotlin and Spring Boot
Victor Warno
Victor Warno

Posted on

Less boilerplate: Crnk with Kotlin and Spring Boot

I grew tired of writing the same code over and over again.

When writing RESTful APIs, you tend to add GET and POST endpoints to your project and as it grows, so do the lines of repetitive code. Not only do your controllers explode - using plain Java leads to writing Getters and Setters in your object classes.

For the latter, best practice is to use Lombok, a library that offers you a variety of Annotations to get rid of the boilerplate code for getting and setting properties. But what about those Controllers?

Introducing Crnk

Somebody told me about crnk.io. Crnk is a library where you only have to define your resources and relations between them, implement the repositories - everything else is taken care of by Crnk: the Controllers, validation, error handling, HATEOAS. It even follows the JSON:API specification for building APIs. So, the format of your responses is consistent throughout the whole application! Bonus points: You even get a nice UI to access your resources.

alt text

I was mesmerized but, personally, I missed a working example with Kotlin. So, I created one myself. If you want to start right away or need such a template, feel free to fork my repository on Github.

Setting up Crnk with Kotlin and Spring Boot from scratch

This is what you have to do if you want to set up Crnk with a Spring Boot project from scratch. With Spring Initializr create a Spring Boot Kotlin project and execute the following steps:

  • Replace mavenCentral with jcenter in the gradle build file
repositories {
    jcenter()
}
Enter fullscreen mode Exit fullscreen mode
  • Import crnk maven bom
configure<io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension> {
    imports {
        mavenBom("io.crnk:crnk-bom:3.2.20200419165537")
    }
}
Enter fullscreen mode Exit fullscreen mode

The versions can be found here.

  • Import crnk dependencies
dependencies {
    implementation("io.crnk:crnk-home")
    implementation("io.crnk:crnk-setup-spring-boot2")
    implementation("io.crnk:crnk-ui")
}
Enter fullscreen mode Exit fullscreen mode
  • Write the code!

Looking at the result, you will notice that you only have to write the model (data class) and to implement the repository (extends a ResourceRepositoryBase). It is important that you need to define a NoArgsConstructor in the data class in order to make it work for Kotlin. But then, all is set and you can say goodbye to keeping in mind all the intricacies of setting up new controllers each time you introduce new resources.


More details and the source code for the template for a Spring Boot Kotlin project with Crnk can be found here.

Oldest comments (0)