将 ObjectMapper 注入 Spring Kafka 序列化器/反序列化器 [英] Inject ObjectMapper into Spring Kafka serialiser/deserialiser
问题描述
我使用 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.
推荐答案
您可以将 JsonSerializer
和 JsonDeserializer
配置为 @Bean
s.向它们注入所需的 ObjectMapper
.并在 DefaultKafkaProducerFactory
和 DefaultKafkaConsumerFactory
bean 定义中使用这些 bean:
You can configure JsonSerializer
and JsonDeserializer
as @Bean
s.
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屋!