0 day streak
java / intermediate
Snippet

Domain-Specific Value Objects using Records with Spring Converter

Using immutable Java record types as strong domain primitives prevents primitive obsession. By registering a Spring Converter, HTTP parameters and path variables are automatically parsed into robust, type-safe domain objects.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public record IsoCurrencyCode(String code) {
public IsoCurrencyCode {
if (code == null || !code.matches("^[A-Z]{3}$")) {
throw new IllegalArgumentException("Invalid ISO currency: " + code);
}
}
}
@Component
public class StringToIsoCurrencyConverter implements Converter<String, IsoCurrencyCode> {
@Override
public IsoCurrencyCode convert(String source) {
return new IsoCurrencyCode(source.trim().toUpperCase());
}
}
spring
Breakdown
1
public record IsoCurrencyCode(String code) {
Declares an immutable domain value object datatype with a single component field.
2
if (code == null || !code.matches("^[A-Z]{3}$")) {
Enforces strict domain validation directly within the record's compact constructor.
3
public class StringToIsoCurrencyConverter implements Converter<String, IsoCurrencyCode> {
Integrates the custom datatype with Spring's ConversionService for seamless binding.