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)
3
votes
yes you can autowire
- pvpkiran
@pvpkiran By autowire will it return the same ObjectMapper bean used by default in Spring-boot.
- Udara Gunathilake
So it will act like a singleton one right..??
- Udara Gunathilake
Yes it will return the same instance
- pvpkiran
@pvpkiran Is there any way(doc) to find the beans that created default by the spring-boot application..?
- Udara Gunathilake
3 Answers
3
votes
1
votes
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;
}
0
votes
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.