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.
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.
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;
}
@Component
public class ObjectMapperProducerFactoryCustomizer implements DefaultKafkaProducerFactoryCustomizer {
private final ObjectMapper objectMapper;
public ObjectMapperProducerFactoryCustomizer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void customize(DefaultKafkaProducerFactory<?, ?> producerFactory) {
if (Objects.nonNull(producerFactory)) {
producerFactory.setValueSerializer(new JsonSerializer<>(objectMapper));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With