t中强制使用Jackson2ObjectMapperBuilde

t中强制使用Jackson2ObjectMapperBuilde

本文介绍了如何在spring-boot中强制使用Jackson2ObjectMapperBuilder?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create my own jackson ObjectMapper bean, as follows:

@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 已执行:

Problem: the bean is never created, but instead the default JacksonAutoConfiguration is executed:

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还不存在。但为什么呢?

So somehow the ObjectMapper bean is not present yet when JacksonAutoConfiguration is evaluated. But why?

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

By debugging with breakpoints I can also see that my bean is never invoked!BUT what I noticed: even though I have the @AutoConfigureBefore, the jackson autoconfig is still run before any of the beans in MyConfig. Strange?

推荐答案

Spring的自定义 ObjectMapper 的文档,这是它说的是:

Here's Spring's documentation for customised ObjectMapper, this is what it says:

如果定义 ObjectMapper bean没有帮助,您可以尝试定义 Jackson2ObjectMapperBuilder bean吗?

If defining ObjectMapper bean does not help, could you try defining Jackson2ObjectMapperBuilder bean instead?

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

Also, could you try defining the beans into a class annotated with @Configuration?

这篇关于如何在spring-boot中强制使用Jackson2ObjectMapperBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:47