What is the advantage of declaring ObjectMapper as a bean?

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();

1 answer

  • answered 2018-05-16 06:15 Mạnh Quyết Nguyễn

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