如何在spring-boot中强制使用Jackson2ObjectMapperBuilder?

时间:2017-09-19 08:18:09

标签: java spring spring-boot jackson

我想创建自己的jackson ObjectMapper bean,如下所示:

@SpringBootApplication
@AutoConfigureBefore(JacksonAutoConfiguration.class) //even this does not help
public class MyConfig extends SpringBootServletInitializer {
    @Bean
    @Primary
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        return builder.createXmlMapper(true).build(); //much more configurations
    }
}

问题:永远不会创建bean,而是执行默认的JacksonAutoConfiguration

package org.springframework.boot.autoconfigure.jackson;

@Configuration
@ConditionalOnClass(ObjectMapper.class)
public class JacksonAutoConfiguration {
        @Bean
        @Primary
        @ConditionalOnMissingBean(ObjectMapper.class)
        public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
            return builder.createXmlMapper(false).build(); //this is always executed!
        }
}

所以当ObjectMapper被评估时,JacksonAutoConfiguration bean还没有出现。但为什么呢?

通过使用断点进行调试,我也可以看到我的bean被从不调用了! 但是我注意到了:即使我有@AutoConfigureBefore,杰克逊自动配置仍然在之前运行 MyConfig中的任何一个bean。奇怪?

1 个答案:

答案 0 :(得分:2)

Here's Spring针对自定义dev_appserver.py的文档,这就是它所说的:

  

如果要完全替换默认的ObjectMapper,也可以   定义该类型的ObjectMapper并将其标记为@Bean,或者,如果您愿意,也可以   基于构建器的方法,定义一个Jackson2ObjectMapperBuilder   @Primary。请注意,在任何一种情况下,这将禁用所有   自动配置ObjectMapper。

如果定义@Bean bean无效,您可以尝试定义ObjectMapper bean吗?

另外,您是否可以尝试将bean定义为使用Jackson2ObjectMapperBuilder注释的类?