What is the advantage of declaring ObjectMapper as a bean? What is the advantage of declaring ObjectMapper as a bean? json json

What is the advantage of declaring ObjectMapper as a bean?


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...)