Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject ObjectMapper into Spring Kafka serialiser/deserialiser

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.

like image 630
wjans Avatar asked Jan 24 '17 16:01

wjans


2 Answers

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;
    }
like image 120
Artem Bilan Avatar answered Oct 22 '22 01:10

Artem Bilan


@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));
        }
    }

}
like image 1
Luram Archanjo Avatar answered Oct 22 '22 03:10

Luram Archanjo