3

I need to use default ObjectMapper inside my Spring-boot application as a singleton instance. Can I simply @autowire the ObjectMapper(Which instance created by default in Spring-boot application) inside my application without creating a @Bean(As I don't want to change any functionalities of ObjectMapper)

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

Udara Gunathilake
  • 202
  • 1
  • 2
  • 14

3 Answers3

3

You don't have to change the funcuntallty, you can just return the Default ObjectMapper

@Configuration
public class ObjectMapperConfig {
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public ObjectMapper objectMapper(){
        return new ObjectMapper();
    }
}
Daniel Taub
  • 5,133
  • 7
  • 42
  • 72
3

TL;DR

Yes, you can.

Explanation

The reason for that is that Spring uses "auto-configuration" and will instantiate that bean for you (as was mentioned) if you haven't created your own. The "instantiation" logic resides inside JacksonAutoConfiguration.java (github link). As you can see, it is a @Bean annotated method with @ConditionalOnMissingBean annotation where the magic happens. It's no different than any other beans auto span up by Spring.

skryvets
  • 2,808
  • 29
  • 31
1

If you know something else is creating it, yes you can just autowire and use it in your 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;
}
Kalpesh Soni
  • 6,879
  • 2
  • 56
  • 59