【问题标题】:How to force Jackson2ObjectMapperBuilder in spring-boot?如何在 spring-boot 中强制 Jackson2ObjectMapperBuilder?
【发布时间】:2017-09-19 08:18:08
【问题描述】:

我想创建自己的jacksonObjectMapper 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!
        }
}

所以在评估JacksonAutoConfiguration 时,不知何故ObjectMapper bean 还不存在。但为什么呢?

通过断点调试,我还可以看到我的 bean 从不被调用! 但我注意到:即使我有@AutoConfigureBefore,jackson 自动配置仍然在MyConfig 中的任何 bean 之前运行。奇怪吗?

【问题讨论】:

  • 只是澄清一下:你在那里放置了调试器断点,它永远不会被调用,对吧?
  • 没错,我的ObjectMapper bean 完全被忽略了(同一个MyConfig 类中的所有其他bean 并非如此。
  • 您能否为您的问题提供更多背景信息?从您所展示的内容来看,尚不清楚应该使用MyConfig。您是否在 IDE 中将应用程序作为 jar、war 或其他方式运行?如果它有一个,它的主要方法是什么样的? minimal, complete, verifiable, example 会让事情变得更清晰。

标签: java spring spring-boot jackson


【解决方案1】:

Here'sSpring 的自定义文档ObjectMapper,是这么写的:

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

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

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

【讨论】:

  • 事实证明我不得不将 bean 定义移动到它自己的 @Configuration 类中。我不知道为什么在主SpringBootApplication 类中会跳过它?
  • 也许@SpringBootApplication 没有扩展@Configuration 注释/接口?无论如何,如果对您有帮助,您可以将答案标记为已接受。
猜你喜欢
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 2022-08-22
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
  • 2014-10-04
相关资源
最近更新 更多