loading...
Cover image for Less boilerplate: Crnk with Kotlin and Spring Boot

Less boilerplate: Crnk with Kotlin and Spring Boot

schmowser profile image Victor Warno ・2 min read

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()
}
  • Import crnk maven bom
configure<io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension> {
    imports {
        mavenBom("io.crnk:crnk-bom:3.2.20200419165537")
    }
}

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")
}
  • 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.

Posted on by:

schmowser profile

Victor Warno

@schmowser

Living the transition from Mathematician to Software Developer. At Senacor Technologies in Germany. Originally from Java - Coding in Java & Javascript.

Discussion

markdown guide