Many Spring Boot developers have written this line at least once:
ObjectMapper mapper = new ObjectMapper();
It works⦠but inside a Spring Boot application, this can silently introduce problems.
Creating ObjectMapper manually bypasses Spring Bootβs Jackson configuration, which means you might lose:
- Registered modules like JavaTimeModule
- Custom serializers/desterilizes
- Global JSON configuration
- Consistent serialization across APIs
Spring Boot already provides a fully configured ObjectMapper as a singleton bean, so the better approach is simply to inject it.
@Service
public class JsonService {
private final ObjectMapper objectMapper;
public JsonService(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
}
This ensures your application uses one consistent JSON configuration everywhere.
Spring Boot also automatically converts objects to JSON in controllers using MappingJackson2HttpMessageConverter, so in many cases you donβt need to use ObjectMapper directly at all.
I wrote a full guide explaining the common mistakes developers make and the correct way to use ObjectMapper in Spring Boot.
π Read the full article:
https://medium.com/write-a-catalyst/stop-creating-objectmapper-instances-in-spring-boot-let-spring-manage-it-21b038252c6b
Top comments (1)
π¬ Have you ever debugged a weird JSON serialization issue caused by multiple ObjectMapper instances?
Waiting to hear from you