7
votes

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.

3

3 Answers

10
votes

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

}
0
votes

For the reactive non-blocking kafka client the configuration is the following:

@Configuration
@EnableConfigurationProperties(KafkaProperties.class)
public class KafkaConfig {

    @Bean
    public ReactiveKafkaProducerTemplate<String, Object> kafkaProducerTemplate(KafkaProperties p,
                                                                               ObjectMapper objectMapper) {
        return new ReactiveKafkaProducerTemplate<>(
                SenderOptions.<String, Object>create(p.buildProducerProperties())
                        .withValueSerializer(new JsonSerializer<>(objectMapper)));
    }
}

the above implies that you are using the io.projectreactor.kafka dep,

dependencies {
    compile "io.projectreactor.kafka:reactor-kafka"
}