Spring Boot中自定义RabbitMQ消息反序列化
我有一个消息层次结构。层次结构中最顶层的消息是使用 @JsonTypeInfo
和 @JsonSubTypes
定义的。班级不在我的控制之下。我用自己的消息扩展了层次结构,并允许 Jackson 反序列化我的消息、定制的 ObjectMapper。通过调试,我发现我需要将子类型注册到“jacksonObjectMapper”bean。所以我的代码如下:
@Component
public class JacksonConfig implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("jacksonObjectMapper")) {
((ObjectMapper) bean).registerSubtypes(new NamedType(ExtendedMessage.class, "ExtendedMessage"));
}
return bean;
}
}
该解决方案有效,但恐怕这是一种解决方法,在 Spring 更新后(例如 bean 名称更改)它将不起作用。是否有记录的方法来自定义用于反序列化消息的 ObjectMapper?
I have a hierarchy of messages. The topmost message in the hierarchy is defined with @JsonTypeInfo
and @JsonSubTypes
. The class is not under my control. I extended the hierarchy with my own message and to allow Jackson to deserialize my message, customized ObjectMapper. By debugging, I figured out that I need to register subtypes to the "jacksonObjectMapper" bean. So my code is as follows:
@Component
public class JacksonConfig implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("jacksonObjectMapper")) {
((ObjectMapper) bean).registerSubtypes(new NamedType(ExtendedMessage.class, "ExtendedMessage"));
}
return bean;
}
}
The solution works, but I'm afraid it's a workaround and it won't work after Spring update (e.g. the bean name changes). Is there a documented way to customize the ObjectMapper that is used to deserialize messages?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
自己构建反序列化器并通过构造函数或设置器将其传递到消费者工厂。
https://docs.spring.io/spring -kafka/docs/current/reference/html/#prog-json
如果您使用 Boot 的自动配置工厂,请使用类似这样的内容
Construct the deserializer yourself and pass it into the consumer factory, via a constructor or setter.
https://docs.spring.io/spring-kafka/docs/current/reference/html/#prog-json
If you are using Boot's auto-configured factory, use something like this