gpt4 book ai didi

java - 用于自定义 ObjectMapper 的 Jax-rs ContextResolver

转载 作者:行者123 更新时间:2023-12-02 09:00:40 25 4
gpt4 key购买 nike

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


@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);
}
}
}

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

希望有帮助。

关于java - 用于自定义 ObjectMapper 的 Jax-rs ContextResolver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60183803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com