【问题标题】:Configure custom ObjectMapper for @RestController within Springboot在 Springboot 中为 @RestController 配置自定义 ObjectMapper
【发布时间】:2021-06-16 08:41:59
【问题描述】:

我在 springboot 应用程序中配置了两个 ObjectMapper。我在如下配置类中声明它们:

@Configuration
public class Config {

  @Bean
  @Primary
  public ObjectMapper getPrimary() {
    return new ObjectMapper();
  }


  @Bean
  public ObjectMapper getSecondary() {
    return new ObjectMapper();
  }

}

@Primary ObjectMapper 可以正常工作。我不知道如何让 @RestController 使用辅助 ObjectMapper。任何帮助表示赞赏。

【问题讨论】:

    标签: json spring spring-boot jackson spring-restcontroller


    【解决方案1】:

    你需要使用限定符:

    @Configuration
    public class Config {
    
      @Bean("myPrimaryOjectMapper")
      @Primary
      public ObjectMapper getPrimary() {
        return new ObjectMapper();
      }
    
    
      @Bean("mySecondaryOjectMapper")
      public ObjectMapper getSecondary() {
        return new ObjectMapper();
      }
    
    }
    

    然后在注入时:

    
    @Autowired
    @Qualifier("mySecondaryOjectMapper")
    private ObjectMapper objectMapper;
    

    您可以在此处阅读更多信息:https://www.baeldung.com/spring-qualifier-annotation#qualifierVsPrimary

    【讨论】:

      【解决方案2】:

      FWIW,我无法让它隐式地与 @RestController 一起工作,但我最终将辅助 ObjectMapper 注入到 rest 控制器中,然后直接使用映射器来解析输入。

      【讨论】:

        猜你喜欢
        • 2021-12-09
        • 1970-01-01
        • 2016-12-18
        • 2020-10-02
        • 1970-01-01
        • 2019-03-25
        • 1970-01-01
        • 2020-01-04
        • 1970-01-01
        相关资源
        最近更新 更多