Use / JavaSLang Futures in Spring-Boot Controllers

25 May

As I’m using VAVR (formerly known as JavaSLang) in my current Spring-Boot project, I was looking for a way to use the futures returned by my services directly instead of converting them to CompletionStages.

My old controller code looked like this:

as you can see, the return type of the controller is set to be a CompletionStage and we have to convert the vavr-future to that data type manually.

Wouldn’t it be much nicer, to simple be able to return the Future<T> type of vavr directly? This is how the controller should look like!

Awesome, so no more converting to CompletableFuture. But how do we get there?

As long as there is no published project containing the following file, we have to add it ourselves:

We’re specifying our own “HandlerMethodReturnValueHandler” . Important here is that it implements the “AsyncHandlerMethodReturnValueHandler” interface which makes sure that Spring will handle this handler before normal handlers that e.g. transform values to json.

After that, we simply need to register this Handler with Spring. Most likely, you already have a WebMvcConfigurer in your project. If yes, just add the “addReturnValueHandlers” method to your existing one or create a completely new one like I did here:

Enjoy using your vavr-futures in your Spring Boot applications now.

In an upcoming post I’ll probably look on how to effectively work with the Either type of Vavr (because I can’t stand these nasty exceptions just to return expected error states!)

Like what you see? Let me know in the comments!

Comment Form