假设我只想要一个 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/