java / intermediate
Snippet
Implementing Custom Type Converters for Spring Data ConversionService
Spring's `ConversionService` provides a unified SPI for executing type conversions between strings and strongly typed domain objects. Implementing `org.springframework.core.convert.converter.Converter<S, T>` allows seamless parsing of raw HTTP request parameters, path variables, and configuration attributes into immutable Java records, keeping web controller action signatures clean and type-safe without manual parsing logic.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public record IsoCurrency(String currencyCode, int fractionDigits) {}@Componentpublic class StringToIsoCurrencyConverter implements Converter<String, IsoCurrency> {@Overridepublic IsoCurrency convert(String source) {if (source == null || source.isBlank()) {return null;}String normalized = source.trim().toUpperCase();Currency currency = Currency.getInstance(normalized);return new IsoCurrency(currency.getCurrencyCode(), currency.getDefaultFractionDigits());}}@Configurationpublic class WebFormattingConfiguration implements WebMvcConfigurer {@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addConverter(new StringToIsoCurrencyConverter());}}
spring
Breakdown
1
public class StringToIsoCurrencyConverter implements Converter<String, IsoCurrency>
Defines a stateless converter contract mapping a source String to a target IsoCurrency record.
2
Currency currency = Currency.getInstance(normalized);
Validates the string representation and parses standard ISO currency metadata.
3
registry.addConverter(new StringToIsoCurrencyConverter());
Registers the converter with Spring MVC's FormatterRegistry for automatic parameter binding.