文章

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 Module are automatically registered with the auto-configured Jackson2ObjectMapperBuilder and are applied to any ObjectMapper instances 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 ObjectMapper completely, either define a @Bean of that type or, if you prefer the builder-based approach, define a Jackson2ObjectMapperBuilder @Bean. When defining an ObjectMapper bean, marking it as @Primary is recommended as the auto-configuration’s ObjectMapper that it will replace is @Primary. Note that, in either case, doing so disables all auto-configuration of the ObjectMapper.

如果你只是想新增模块而不是完全自定义ObjectMapper,你只需要提供Module的Bean即可,比如下面这样

@Configuration
public class JacksonConfig {
    @Bean
    public CustomLongToStringModule customLongToStringModule() {
        return new CustomLongToStringModule();
    }

    @Bean
    public CustomBigDecimalToStringModule customBigDecimalToStringModule() {
        return new CustomBigDecimalToStringModule();
    }
}

License:  CC BY 4.0