Jax-rs ContextResolver for custom 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;
}
}

小心点。你混合了 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);
}
}
}

然后,您可以使用@AutowiredObjectMapper注入到需要它的类中。(如果需要,请查看此链接:在 Spring 中配置 ObjectMapper(

希望对您有所帮助。

最新更新