Spring MVC为ObjectMapper注册模块
网上大部分中文教程都会让你提供直接ObjectMapper的Bean,在Bean方法中注册模块,例如下面这样
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(customLongToStringModule());
objectMapper.registerModule(customBigDecimalToStringModule());
return objectMapper;
}
}但上面这种做法会导致Spring MVC提供的ObjectMapper自动配置的模块失效,根据官方文档:
Any beans of type
Moduleare automatically registered with the auto-configuredJackson2ObjectMapperBuilderand are applied to anyObjectMapperinstances that it creates. This provides a global mechanism for contributing custom modules when you add new features to your application.If you want to replace the default
ObjectMappercompletely, either define a@Beanof that type or, if you prefer the builder-based approach, define aJackson2ObjectMapperBuilder@Bean. When defining anObjectMapperbean, marking it as@Primaryis recommended as the auto-configuration’sObjectMapperthat it will replace is@Primary. Note that, in either case, doing so disables all auto-configuration of theObjectMapper.
如果你只是想新增模块而不是完全自定义ObjectMapper,你只需要提供Module的Bean即可,比如下面这样
@Configuration
public class JacksonConfig {
@Bean
public CustomLongToStringModule customLongToStringModule() {
return new CustomLongToStringModule();
}
@Bean
public CustomBigDecimalToStringModule customBigDecimalToStringModule() {
return new CustomBigDecimalToStringModule();
}
}