将 ObjectMapper 注入 Spring Kafka 序列化器/反序列化器 [英] Inject ObjectMapper into Spring Kafka serialiser/deserialiser

查看:64
本文介绍了将 ObjectMapper 注入 Spring Kafka 序列化器/反序列化器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Spring Kafka 1.1.2-RELEASE 和 Spring Boot 1.5.0 RC,并且我配置了一个自定义值序列化器/反序列化器类扩展 org.springframework.kafka.support.serializer.JsonSerializer/org.springframework.kafka.support.serializer.JsonDeserializer.这些类确实使用了可以通过构造函数提供的 Jackson ObjectMapper.

I'm using Spring Kafka 1.1.2-RELEASE with Spring Boot 1.5.0 RC and I have configured a custom value serialiser/deserialiser class extending org.springframework.kafka.support.serializer.JsonSerializer/org.springframework.kafka.support.serializer.JsonDeserializer. These classes do use a Jackson ObjectMapper which can be provided through the constructor.

是否有可能从我的 Spring 上下文中注入 ObjectMapper?我已经配置了一个 ObjectMapper,我想在序列化器/反序列化器中重用它.

Is it somehow possible to inject the ObjectMapper from my Spring context? I have an ObjectMapper configured already which I would like to reuse in the serialiser/deserialiser.

推荐答案

您可以将 JsonSerializerJsonDeserializer 配置为 @Beans.向它们注入所需的 ObjectMapper.并在 DefaultKafkaProducerFactoryDefaultKafkaConsumerFactory bean 定义中使用这些 bean:

You can configure JsonSerializer and JsonDeserializer as @Beans. Inject a desired ObjectMapper to them. And use those beans in the DefaultKafkaProducerFactory and DefaultKafkaConsumerFactory bean definitions:

    @Bean
    public ProducerFactory<Integer, String> producerFactory() {
        DefaultKafkaProducerFactory<Integer, String> producerFactory = 
                new DefaultKafkaProducerFactory<>(producerConfigs());
        producerFactory.setValueSerializer(jsonSerializer());
        return producerFactory;
    }

这篇关于将 ObjectMapper 注入 Spring Kafka 序列化器/反序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆