Spring boot Springboot应用程序中的Autowire对象映射器

Spring boot Springboot应用程序中的Autowire对象映射器,spring-boot,jackson,objectmapper,Spring Boot,Jackson,Objectmapper,我需要在Spring boot应用程序中使用默认的ObjectMapper作为单例实例。我可以在我的应用程序中简单地@autowire ObjectMapper(在Spring boot应用程序中默认创建的实例),而不创建@Bean(因为我不想更改ObjectMapper的任何功能) 您不必更改函数属性,只需返回默认的ObjectMapper @Configuration public class ObjectMapperConfig { @Bean @Scope(Configu

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


您不必更改函数属性,只需返回默认的
ObjectMapper

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

如果您知道有其他东西在创建它,是的,您可以自动连线并在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;
}
TL;DR

是的,你可以

解释


原因是Spring使用“自动配置”,如果您还没有创建自己的bean,它将为您实例化该bean(如前所述)。“实例化”逻辑驻留在JacksonAutoConfiguration.java中。如您所见,它是一个带有
@conditionalnmissingbean
注释的
@Bean
注释方法,魔法就在这里发生。它和其他豆子一样,在春天自动变长。

是的,你可以autowire@pvpkiran通过autowire,它将返回与Spring-boot中默认使用的ObjectMapper bean相同的对象映射程序bean。因此,它将像singleton bean一样工作。对吗?是的,它将返回相同的对象映射程序beaninstance@pvpkiran有办法吗(博士)如果我不想创建一个ObjectMapperConfig类并返回一个与您的示例类似的bean,那么是否要查找由spring引导应用程序创建默认值的bean。我可以自动连接SpringBoot已经创建的默认objectMapper吗?在没有@scope注释的情况下尝试一下我真的需要创建一个Bean吗?如果你想自动连接objectMapper,而spring还没有创建一个梁,那么是的,这就是我真的想知道的。我列出了bean列表,ObjectMapper也是由Spring创建的。这意味着我不需要创建一个单独的bean,对吗。?