java / intermediate
Snippet
Custom Data Conversion with Converter SPI
Implementing the Converter interface allows Spring to automatically transform one type to another, such as converting a path variable ID into a full User object.
snippet.java
1
2
3
4
5
6
7
@Componentpublic class StringToUserConverter implements Converter<String, User> {@Overridepublic User convert(String source) {return new User(Long.parseLong(source));}}
spring
Breakdown
1
Converter<S, T>
A functional interface for converting a source object of type S to a target object of type T.
2
@Component
Registering the converter as a bean allows Spring's ConversionService to pick it up automatically.