如何在spring-boot中强制使用Jackson2ObjectMapperBuilder? [英] How to force Jackson2ObjectMapperBuilder in spring-boot?

查看:8314
本文介绍了如何在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 并将其标记为 @Primary ,或者,如果您更喜欢
基于构建器的方法,请定义Jackson2ObjectMapperBuilder
@Bean 。请注意,在任何一种情况下,这都将禁用ObjectMapper的所有
自动配置。

If you want to replace the default ObjectMapper completely, either define a @Bean of that type and mark it as @Primary, or, if you prefer the builder-based approach, define a Jackson2ObjectMapperBuilder @Bean. Note that in either case this will disable all auto-configuration of the ObjectMapper.

如果定义 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆