将ObjectMapper声明为Bean有什么好处? [英] What is the advantage of declaring ObjectMapper as a bean?

查看:476
本文介绍了将ObjectMapper声明为Bean有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我只想要一个ObjectMapper对象的普通实例.将其声明为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();
}

为什么不每次需要时都用new ObjectMapper()创建一个新的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();

推荐答案

以下是有关

映射器实例是完全线程安全的 ,前提是实例的所有配置都在ANY读或写调用之前进行.如果在首次使用后修改了映射器的配置,则更改可能会或可能不会生效,并且配置调用本身可能会失败.

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.

这是提高杰克逊性能的指南:

重用重量级对象:ObjectMapper(数据绑定)和JsonFactory(流API) 在较小程度上,您可能还想重用ObjectReader和ObjectWriter实例-这只是锦上添花,但它们是完全线程安全的和可重用的

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

所以总结一下:

  • ObjectMapper是线程安全的,只要您没有即时更改配置

  • ObjectMapper is thread-safe, as long as you did not change your configuration on the fly

ObjectMapper初始化是一项繁重的操作

ObjectMapper initialization is a heavy operation

因此,将您的ObjectMapper声明为@Bean将:

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)

您的ObjectMapper已完全配置.这是线程安全的. (但显然,请勿修改@Autowired实例XD)

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

这篇关于将ObjectMapper声明为Bean有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆