在 Spring Boot 应用程序中自动装配 ObjectMapper

Posted

技术标签:

【中文标题】在 Spring Boot 应用程序中自动装配 ObjectMapper【英文标题】:Autowire ObjectMapper in Springboot application 【发布时间】:2018-07-28 09:41:54 【问题描述】:

我需要在我的 Spring-boot 应用程序中使用默认的 ObjectMapper 作为单例实例。我可以在我的应用程序中简单地@autowire ObjectMapper(Spring-boot 应用程序中默认创建的实例)而不创建@Bean(因为我不想更改 ObjectMapper 的任何功能)

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper

【问题讨论】:

是的,你可以自动接线 @pvpkiran 通过自动连接,它将返回 Spring-boot 中默认使用的相同 ObjectMapper bean。 所以它会像单身一样对..?? 是的,它会返回相同的实例 @pvpkiran 有什么方法(doc)可以找到 spring-boot 应用程序默认创建的 bean..? 【参考方案1】:

TL;DR

是的,你可以。

说明

原因是 Spring 使用“自动配置”并且如果您还没有创建自己的 bean,它将为您实例化该 bean(如前所述)。 “实例化”逻辑位于JacksonAutoConfiguration.java (github link) 中。如您所见,这是一个带有@ConditionalOnMissingBean 注释的@Bean 注释方法,其中发生了神奇的事情。它与 Spring 自动生成的任何其他 bean 没有什么不同。

【讨论】:

【参考方案2】:

如果您知道其他东西正在创建它,是的,您可以自动装配并在您的 bean 中使用它

@Lazy
@Autowired
ObjectMapper mapper;

@PostConstruct
public ObjectMapper configureMapper() 
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);

    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, true);
    mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

    SimpleModule module = new SimpleModule();
    module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
    module.addSerializer(LocalDate.class, new LocalDateSerializer());
    mapper.registerModule(module);

    return mapper;

【讨论】:

【参考方案3】:

您不必更改功能,只需返回默认ObjectMapper

@Configuration
public class ObjectMapperConfig 
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public ObjectMapper objectMapper()
        return new ObjectMapper();
    

【讨论】:

如果我不想创建 ObjectMapperConfig 类并返回像您的示例一样的 bean。我可以自动装配 SpringBoot 已经创建的默认 objectMapper 吗? 不带@scope注解试试 我真的需要创建一个 Bean..吗? 如果你想自动装配 objectmapper,而 spring 还没有创建一个梁,那么是的 是的,我真的很想知道。我列出了 bean 列表,并且 ObjectMapper 也是由 Spring 创建的。所以这意味着我不会创建一个单独的 bean 对吧。?

以上是关于在 Spring Boot 应用程序中自动装配 ObjectMapper的主要内容,如果未能解决你的问题,请参考以下文章