Let's say I just want a plain instance of ObjectMapper
object. Is there any advantage to declare it as a bean?
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
Why not just make a new ObjectMapper
by new ObjectMapper()
every time we need it?
Or declare it as a static object?
private static final ObjectMapper mapper = new ObjectMapper();
ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model ( JsonNode ), as well as related functionality for performing conversions.
Overview. When using JSON format, Spring Boot will use an ObjectMapper instance to serialize responses and deserialize requests. In this tutorial, we'll take a look at the most common ways to configure the serialization and deserialization options. To learn more about Jackson, be sure to check out our Jackson tutorial.
The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON. The Jackson ObjectMapper can also create JSON from Java objects.
Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls.
Here is the API note about ObjectMapper
Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls. If configuration of a mapper is modified after first usage, changes may or may not take effect, and configuration calls themselves may fail.
And here is guideline to improve jackson performance:
Reuse heavy-weight objects: ObjectMapper (data-binding) and JsonFactory (streaming API) To a lesser degree, you may also want to reuse ObjectReader and ObjectWriter instances -- this is just some icing on the cake, but they are fully thread-safe and reusable
So to summarize:
ObjectMapper
is thread-safe, as long as you did not change your configuration on the fly
ObjectMapper
initialization is a heavy operation
Therefore, declare your ObjectMapper
as @Bean
will:
Improve parsing performance (as you do not need to re-init the instance when parsing)
Reduce memory usage (less objects created)
Your ObjectMapper
returned from @Bean
method is fully configured. It is thread-safe. (But do obviously, do not modify the @Autowired
instance XD)
Give common configuration for your application (like timezone, null fail-over config...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With