将ObjectMapper声明为Bean有什么好处? [英] What is the advantage of declaring ObjectMapper as a 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 所以总结一下: 因此,将您的 Therefore, declare your 提高解析性能(因为解析时无需重新初始化实例) Improve parsing performance (as you do not need to re-init the instance when parsing) 减少内存使用(减少创建的对象) Reduce memory usage (less objects created) 您的 Your 为您的应用程序提供通用配置(例如时区,空故障转移配置...) Give common configuration for your application (like timezone, null fail-over config...) 这篇关于将ObjectMapper声明为Bean有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
ObjectMapper
是线程安全的,只要您没有即时更改配置
ObjectMapper
is thread-safe, as long as you did not change your configuration on the flyObjectMapper
初始化是一项繁重的操作ObjectMapper
initialization is a heavy operationObjectMapper
声明为@Bean
将:ObjectMapper
as @Bean
will:
ObjectMapper
已完全配置.这是线程安全的. (但显然,请勿修改@Autowired
实例XD)ObjectMapper
returned from @Bean
method is fully configured. It is thread-safe. (But do obviously, do not modify the @Autowired
instance XD)