我应该将 Jackson 的 ObjectMapper 声明为静态字段吗? [英] Should I declare Jackson's ObjectMapper as a static field?

查看:30
本文介绍了我应该将 Jackson 的 ObjectMapper 声明为静态字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

杰克逊图书馆的 ObjectMapper似乎是线程安全的.

The Jackson library's ObjectMapper class seems to be thread safe.

这是否意味着我应该将我的 ObjectMapper 声明为这样的静态字段

Does this mean that I should declare my ObjectMapper as a static field like this

class Me {
    private static final ObjectMapper mapper = new ObjectMapper();
}

而不是像这样的实例级字段?

instead of as an instance-level field like this?

class Me {
    private final ObjectMapper mapper = new ObjectMapper();
}

推荐答案

是的,这是安全的,值得推荐.

Yes, that is safe and recommended.

您引用的页面中唯一的警告是,一旦共享映射器,您就无法修改它的配置;但你没有改变配置,所以很好.如果您确实需要更改配置,您可以从静态块中进行更改,也可以.

The only caveat from the page you referred is that you can't be modifying configuration of the mapper once it is shared; but you are not changing configuration so that is fine. If you did need to change configuration, you would do that from the static block and it would be fine as well.

编辑:(2013/10)

在 2.0 及以上版本中,可以通过注意到有一个更好的方法来扩充上面的内容:使用 ObjectWriterObjectReader 对象,它们可以由 构造对象映射器.它们是完全不可变的、线程安全的,这意味着理论上甚至不可能导致线程安全问题(如果代码尝试重新配置实例,ObjectMapper 可能会发生这种情况).

With 2.0 and above, above can be augmented by noting that there is an even better way: use ObjectWriter and ObjectReader objects, which can be constructed by ObjectMapper. They are fully immutable, thread-safe, meaning that it is not even theoretically possible to cause thread-safety issues (which can occur with ObjectMapper if code tries to re-configure instance).

这篇关于我应该将 Jackson 的 ObjectMapper 声明为静态字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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