【问题标题】:Spring Bean Overriding My ObjectMapper ConfigurationSpring Bean 覆盖我的 ObjectMapper 配置
【发布时间】:2020-03-13 21:38:02
【问题描述】:

今天遇到一个问题,当涉及到我试图做的一些 ObjectMapper 配置时,与配置相关的依赖项不断获胜。我将以下内容添加到我的 Spring Boot 应用程序中。

@Configuration
public class CustomObjectMapperConfig {

    @Autowired
    public void configureObjectMapper(ObjectMapper objectMapper) {
        objectMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }

}

我实际上宁愿不使用时间戳,但为了向后兼容,我必须这样做。我在这里有问题的行上放了一个调试点,它被击中了,但我不断收到以 ISO 格式返回给我的日期,这是大多数项目或我们项目的默认格式。

【问题讨论】:

    标签: spring spring-boot objectmapper


    【解决方案1】:

    我终于发现我引入的公司依赖项具有以下内容:

    @Configuration
    public class ObjectMapperPropertiesConfig {
        /**
         * @deprecated Spring boot jackson properties should be used instead.
         */
        @Deprecated
        @Autowired
        public void setObjectMapper(
                final ObjectMapper objectMapper) {
            objectMapper
                .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, !ignoreUnknown);
        }
    ...
    

    这个类是在我的课之后加载的,所以它总是在 WRITE_DATES_AS_TIMESTAMPS 功能方面获胜。

    为了解决这个问题,我最终添加了 @DependsOn 注释。这迫使另一个 bean 首先加载,让我的 bean 有机会赢得配置战。很难找到 bean 的正确名称。它最终看起来像这样:

    @DependsOn("path.to.object.ObjectMapperPropertiesConfig")
    

    注意:这里的@Deprecated 注释告诉我,该代码将在未来的版本中消失,以支持 Spring Boot 属性。目前,我的更改将生效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      相关资源
      最近更新 更多