java - 将 ObjectMapper 声明为 bean 有什么好处?

标签 java json oop static jackson

假设我只想要一个 ObjectMapper 对象的普通实例。将其声明为 bean 有什么好处吗?

@Bean
public ObjectMapper objectMapper() {
    return new ObjectMapper();
}

为什么不每次需要时都通过 new ObjectMapper() 创建一个新的 ObjectMapper 呢?

或者将其声明为静态对象?

private static final ObjectMapper mapper = new ObjectMapper();

最佳答案

这里是关于 ObjectMapper 的 API 说明

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.

这是 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

总结一下:

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

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

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

  • 提高解析性能(解析时不需要重新初始化实例)

  • 减少内存使用(创建更少的对象)

  • @Bean 方法返回的 ObjectMapper 已完全配置。它是线程安全的。 (但显然,不要修改 @Autowired 实例 XD)

  • 为您的应用程序提供通用配置(例如时区、空故障转移配置...)

关于java - 将 ObjectMapper 声明为 bean 有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50362883/

相关文章:

java - 与在 PHP 中运行的应用程序接口(interface)?

json - 我在 Swift 5 上解码 json 时出错

javascript - Google 图表堆积柱的 JSON 格式

c# - 接口(interface)应该尽可能通用吗?

php - PHP 高级 OOP 特性的真实示例

java - 将 draftCompile 传递给 IntelliJ IDEA 的 GWT 编译器

java - 为每个元素添加一个按钮到 ListView

java - 绘制形状时,形状属性未在类之间正确传递 - Java Swing

javascript - 在javascript中解析json对象以获取键和值

c# - 是否有一个类别中所有可定义项目的包容性术语?