【问题标题】:Spring Boot ignore ObjectMapper moduleSpring Boot 忽略 ObjectMapper 模块
【发布时间】:2023-03-15 00:25:01
【问题描述】:

在应用程序上下文中,我注册了一个 ObjectMapper 模块:

@Bean
public SimpleModule jsr310Module() {
    final SimpleModule module = new SimpleModule();
    module.addSerializer(new LocalDateSerializer());
    module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
    return module;
}

我尝试调试并加载它(或者至少方法 public void setupModule(SetupContext context) 是在启动时执行) 但是当我调用一个返回带有 LocalDate 对象的 rest API 时,我的反序列化器被忽略了。

解决问题的一些提示?

【问题讨论】:

  • 您是如何注册 ObjectMapper 的?因为 SimpleModule 需要注入到 ObjectMapper 中。
  • 我没有配置,模块应该是默认配置的,它做到了……我也可以用另一种方式,你有什么建议?
  • 你可以看看 spring-boot 中的 JacksonAutoConfiguration 类并尝试调试一下。我正在阅读它并试图弄清楚它是如何管理配置 ObjectMapper 的。看起来如果LocalDateDeserializer 类(来自版本 1.2.2)在类路径中,它应该作为JodaDateTimeJacksonConfiguration 的一部分自动加载。 (我仍然无法理解这种类型的配置:S)
  • @rascio “当我调用返回带有 LocalDate 的对象的 rest API 时,我的反序列化器被忽略。”你的意思是 serializer 被忽略了吗?
  • 是的,对不起...最后我解决了,是我错过了扩展WebMvcAutoConfiguration类...

标签: jackson spring-boot jodatime


【解决方案1】:

要使其工作,@Configuration 类应扩展 WebMvcAutoConfiguration

【讨论】:

  • 这个人怎么知道:(?文档中没有提到只是Any beans of type com.fasterxml.jackson.databind.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.
【解决方案2】:

根据Spring Boot documentation,要配置ObjectMapper,您可以自己定义bean并使用@Bean@Primary对其进行注释。在那里你可以注册模块。或者,您可以添加一个 Jackson2ObjectMapperBuilder 类型的 bean,您可以在其中自定义 ObjectMapper。

【讨论】:

  • 您链接的相同文档还说“自定义 Jackson 的另一种方法是将 com.fasterxml.jackson.databind.Module 类型的 bean 添加到您的上下文中。它们将在每个 bean 中注册类型 ObjectMapper,为您在应用程序中添加新功能时提供自定义模块提供全局机制。”看起来这就是原始海报试图做的事情。
猜你喜欢
  • 2019-04-21
  • 2016-09-04
  • 1970-01-01
  • 2017-05-04
  • 2015-08-03
  • 2016-08-19
  • 2018-06-22
  • 2014-11-25
  • 2016-08-01
相关资源
最近更新 更多