Partner – Microsoft – NPI (cat= Spring)
announcement - icon

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

And, the Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

You can also ask questions and leave feedback on the Azure Spring Apps GitHub page.

1. Overview

In this tutorial, we’ll explore different ways to implement case-insensitive enum mapping in Spring Boot.

First, we’ll see how enums are mapped by default in Spring. Then, we’ll learn how to tackle the case sensitivity challenge.

2. Default Enum Mapping in Spring

Spring relies upon several built-in converters to handle string conversion when dealing with request parameters.

Typically, when we pass an enum as a request parameter, it uses StringToEnumConverterFactory under the hood to convert the passed String to an enum.

By design, this converter is called Enum.valueOf(Class, String), which means that the given string must match exactly one of the declared enum constants.

For instance, let’s consider the Level enum:

public enum Level {
    LOW, MEDIUM, HIGH
}

Next, let’s create a handler method that accepts our enum as an argument:

@RestController
@RequestMapping("enummapping")
public class EnumMappingController {

    @GetMapping("/get")
    public String getByLevel(@RequestParam(name = "level", required = false) Level level){
        return level.name();
    }

}

Let’s send a request to http://localhost:8080/enummapping/get?level=MEDIUM using CURL:

curl http://localhost:8080/enummapping/get?level=MEDIUM

The handler method sends back MEDIUM, the name of the enum constant MEDIUM.

Now, let’s pass medium instead of MEDIUM and see what happens:

curl http://localhost:8080/enummapping/get?level=medium
{"timestamp":"2022-11-18T18:41:11.440+00:00","status":400,"error":"Bad Request","path":"/enummapping/get"}

As we can see, the request is considered invalid, and the application fails with an error:

Failed to convert value of type 'java.lang.String' to required type 'com.baeldung.enummapping.enums.Level'; 
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam com.baeldung.enummapping.enums.Level] for value 'medium'; 
...

Looking at the stack trace, we can see that Spring throws ConversionFailedException. It doesn’t recognize the medium as an enum constant.

3. Case-Insensitive Enum Mapping

Spring provides several convenient approaches to solve the problem of case sensitivity when mapping enums.

Let’s take a close look at each approach.

3.1. Using ApplicationConversionService

The ApplicationConversionService class comes with a set of configured converters and formatters.

Among these out-of-the-box converters, we find StringToEnumIgnoringCaseConverterFactory. As the name implies, it converts a string into an enum in a case-insensitive manner.

First, we need to add and configure ApplicationConversionService:

@Configuration
public class EnumMappingConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        ApplicationConversionService.configure(registry);
    }
}

This class configures the FormatterRegistry with ready-to-use converters appropriate for most Spring Boot applications.

Now, let’s confirm that everything works as expected using a test case:

@RunWith(SpringRunner.class)
@WebMvcTest(EnumMappingController.class)
public class EnumMappingIntegrationTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void whenPassingLowerCaseEnumConstant_thenConvert() throws Exception {
        mockMvc.perform(get("/enummapping/get?level=medium"))
            .andExpect(status().isOk())
            .andExpect(content().string(Level.MEDIUM.name()));
    }

}

As we can see, the medium value passed as a parameter is successfully converted to MEDIUM.

3.2. Using Custom Converter

Another solution would be using a custom converter. Here, we will be using the Apache Commons Lang 3 library.

First, we need to add its dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

The basic idea here is to create a converter that converts a string representation of a Level constant to a real Level constant:

public class StringToLevelConverter implements Converter<String, Level> {

    @Override
    public Level convert(String source) {
        if (StringUtils.isBlank(source)) {
            return null;
        }
        return EnumUtils.getEnum(Level.class, source.toUpperCase());
    }

}

From a technical point of view, a custom converter is a simple class that implements the Converter<S,T> interface.

As we can see, we converted the String object to uppercase. Then, we used the EnumUtils utility class from the Apache Commons Lang 3 library to get the Level constant from the upper case string.

Now, let’s add the last missing piece of the puzzle. We need to tell Spring about our new custom converter. To do so, we’ll use the same FormatterRegistry from before. It provides the addConverter() method to register custom converters:

@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addConverter(new StringToLevelConverter());
}

And that’s it. Our StringToLevelConverter is now available in the ConversionService.

Now, we can use it in the same way as any other converter:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = EnumMappingMainApplication.class)
public class StringToLevelConverterIntegrationTest {

    @Autowired
    ConversionService conversionService;

    @Test
    public void whenConvertStringToLevelEnumUsingCustomConverter_thenSuccess() {
        assertThat(conversionService.convert("low", Level.class)).isEqualTo(Level.LOW);
    }

}

As shown above, the test case confirms that the “low” value is converted to Level.LOW.

3.3. Using Custom Property Editor

Spring uses multiple built-in property editors under the hood to manage conversion between String values and Java objects.

Similarly, we can create a custom property editor to map String objects into Level constants.

For instance, let’s name our custom editor LevelEditor:

public class LevelEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) {
        if (StringUtils.isBlank(text)) {
            setValue(null);
        } else {
            setValue(EnumUtils.getEnum(Level.class, text.toUpperCase()));
        }
    }
}

As we can see, we need to extend the PropertyEditorSupport class and override the setAsText() method.

The idea of overriding setAsText() is to convert the uppercase version of the given string into the Level enum.

It’s worth noting that PropertyEditorSupport provides getAsText() as well. It’s called when serializing a Java object to a string. So, we don’t need to override it here.

We need to register our LevelEditor because Spring doesn’t automatically detect custom property editors. To do that, we need to create a method annotated with @InitBinder in our Spring controller:

@InitBinder
public void initBinder(WebDataBinder dataBinder) {
    dataBinder.registerCustomEditor(Level.class, new LevelEditor());
}

Now that we put all the pieces together, let’s confirm that our custom property editor LevelEditor works using a test case:

public class LevelEditorIntegrationTest {

    @Test
    public void whenConvertStringToLevelEnumUsingCustomPropertyEditor_thenSuccess() {
        LevelEditor levelEditor = new LevelEditor();
        levelEditor.setAsText("lOw");

        assertThat(levelEditor.getValue()).isEqualTo(Level.LOW);
    }
}

Another important thing to mention here is that EnumUtils.getEnum() returns the enum when found, null otherwise.

So, to avoid NullPointerException, we need to change our handler method a little bit:

public String getByLevel(@RequestParam(required = false) Level level) {
    if (level != null) {
        return level.name();
    }
    return "undefined";
}

Now, let’s add a simple test case to test this:

@Test
public void whenPassingUnknownEnumConstant_thenReturnUndefined() throws Exception {
    mockMvc.perform(get("/enummapping/get?level=unknown"))
        .andExpect(status().isOk())
        .andExpect(content().string("undefined"));
}

4. Conclusion

In this article, we learned a variety of ways to implement case-insensitive enum mapping in Spring.

Along the way, we looked at some ways to do this using built-in and custom converters. Then, we saw how to achieve the same objective using a custom property editor.

As always, the code used in this article can be found over on GitHub.

Course – LS (cat=Spring)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.