Spring Boot: How to ignore case when using an Enum as a Request parameter
Here is a way to enable the use of case-insensitive enumerations request parameters. You won’t need to do any code modification in your enum.
Let’s say you have a controller class:
@RestController
public class MyController {
@GetMapping("/test/{myEnum}")
public String getMyEnum(@PathVariable MyEnum myEnum) {
return "Hey " + myEnum;
}
}
And an Enumeration:
public enum MyEnum {
HEY,
HELLO
}
You have to create a custom Spring converter that converts String into MyEnum:
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class MyEnumConverter implements Converter<String, MyEnum> {
@Override
public MyEnum convert(String value) {
return MyEnum.valueOf(value.toUpperCase());
}
}
Tests:
GET /test/hEy
will returnHey HEY
GET /test/HELLO
will returnHey HELLO
GET /test/hello
will returnHey HELLO
Tested with Spring Boot 2.2.6