In this tutorial, we will see how we can use the Vavr Option data type in the Spring URL parameter RequestParam. The end goal is to be able to write the controller function signature like this:

@GetMapping
List<CustomerDtoResp> getCustomers(@RequestParam(required = false) Option<String> city)

Like that, instead of getting city=null when absent from URL, we will get city=Option.None. This allows for better code quality, not having to think whether to check for null or not. Also, that ensures null-safety Java code.

In our example, we may call .fold() on the Option, and redirect toward the corresponding repository function (depending on whether city is present or not):

var customers = city.fold(customerRepository::findAllF, customerRepository::findAllByCity);

Finally, this forces the code flow to be better, as .fold() is a total function, ie. it returns a result in all cases.

To do this, we just need to override some Spring Web functions (the ones extracting the RequestParam from the URL), using the LibCustom library. First, add this dependency to your pom.xml:

<dependency>
    <groupId>io.github.jleblanc64</groupId>
    <artifactId>lib-custom</artifactId>
    <version>1.0.7</version>
</dependency>

A good place to load the custom code is in the Spring config function:

import io.github.jleblanc64.libcustom.LibCustom;
import io.github.jleblanc64.libcustom.custom.spring.VavrSpring6;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;

@Bean
public DataSource getDataSource() {
    VavrSpring6.override();
    LibCustom.load();
    (...)

Indeed, this code is executed early in the application lifecycle. You can load the custom code in other places of your code, as long as it is executed before the Spring Boot application is fully started. For instance, a static code snippet in a config file is a good choice.

You can see a full working Spring Boot app that uses these strategies in my Github repo. You may leave a question in the issues if you need.


<
Previous Post
Use Vavr List and Option in Spring 6 JPA repository
>
Next Post
Java JUnit: programmatically setup a test retry mechanism