【问题标题】:Jax-rs ContextResolver for custom ObjectMapper用于自定义 ObjectMapper 的 Jax-rs ContextResolver
【发布时间】:2020-05-27 17:50:03
【问题描述】:

我不确定如何将我在下面创建的自定义 objectMapper 注册为 bean,并通过构造函数或 Autowire 将其作为依赖项注入到其他对象中


@SpringBootApplication
public class DemoApplication {

@Bean
//how to register it as a bean here and inject wherever I need to via @Inject or @Autowire

public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}


@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
    private final ObjectMapper objectMapper = new ObjectMapper();

    public ObjectMapperProvider() {
        this.objectMapper.disable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
    }

    @Override
    public ObjectMapper getContext(final Class<?> type) {
        return objectMapper;
    }
}

【问题讨论】:

    标签: java spring spring-boot jax-rs resolver


    【解决方案1】:

    对此要小心。您正在混合 Jax-RS 和 Spring,但您必须知道一些事情:Spring 没有完全实现 Jax-RS 规范……原因是什么? Spring MVC 与 JAX-RS 几乎同时开发,在 JAX-RS 发布后,他们从未迁移来实现这一点(谁会这样做)?

    使用 Spring 声明自己的 ObjectMapper 的最佳方式如下:

    @SpringBootApplication
    public class DemoApplication {
    
        @Bean
        public ObjectMapper objectMapper() {
            ObjectMapper objectMapper = new ObjectMapper();
            // DO what you want;
            return objectMapper;
        }
    
        public static void main(String[] args) {
                SpringApplication.run(DemoApplication.class, args);
            }
        }
    }
    

    然后,您可以使用@Autowired 将您的ObjectMapper 注入需要它的类中。 (如果需要,请查看此链接:Configuring ObjectMapper in Spring

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 2011-07-04
      • 2013-03-15
      • 2013-09-17
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多