Spring Boot中自定义RabbitMQ消息反序列化

发布于 2025-01-15 18:19:47 字数 720 浏览 7 评论 0原文

我有一个消息层次结构。层次结构中最顶层的消息是使用 @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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百善笑为先 2025-01-22 18:19:47

自己构建反序列化器并通过构造函数或设置器将其传递到消费者工厂。

https://docs.spring.io/spring -kafka/docs/current/reference/html/#prog-json

如果您使用 Boot 的自动配置工厂,请使用类似这样的内容

@Bean
JsonDeserializer deser(ConsumerFactory<Object, Object> cf) {
     ...
     cf.setDeserializer(...);
}

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

@Bean
JsonDeserializer deser(ConsumerFactory<Object, Object> cf) {
     ...
     cf.setDeserializer(...);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文