Video in progress

Strong Middle 🌱 Spring

What do you write in Spring MVC to automatically convert a request parameter or path variable into your own type (for example OrderId)?

You write a Converter<String, T> or a Formatter<T> and register it through WebMvcConfigurer.addFormatters (in Boot, just being a bean is enough). Then the controller parameter is directly an OrderId, and a bad value returns 400.

📖 Answer

Say the order number looks like ORD-2024-000123, and in code it's record OrderId(int year, long seq).

@Component
class OrderIdConverter implements Converter<String, OrderId> {
    private static final Pattern P = Pattern.compile("ORD-(\\d{4})-(\\d{6})");

    @Override
    public OrderId convert(String source) {
        Matcher m = P.matcher(source);
        if (!m.matches()) {
            throw new IllegalArgumentException("Noto'g'ri buyurtma raqami: " + source);
        }
        return new OrderId(Integer.parseInt(m.group(1)), Long.parseLong(m.group(2)));
    }
}

@GetMapping("/api/orders/{id}")
OrderDto get(@PathVariable OrderId id) { ... }

Boot adds Converter, GenericConverter and Formatter beans to MVC by itself. In plain Spring MVC you call registry.addConverter(...) inside WebMvcConfigurer.addFormatters(registry).

If the converter throws an exception, Spring wraps it in MethodArgumentTypeMismatchException, and by default that gives 400 Bad Request, not 500. Catch that exception in the advice and give a clear message.

A Formatter differs in that it's two-way (parse and print) and receives the Locale. It's handy in language-dependent cases like accepting an amount written as "1 250 000,50".

One thing that gets confused a lot: this mechanism is only for request parameters, path, headers and form fields. With a JSON body (@RequestBody), Jackson does the work, and to change a type there you need a JsonDeserializer or a @JsonCreator in a record.