I had an issue with injecting a custom ObjectMapper
into Spring Kafka serializer which I have resolved with this answer, LocalDateTime
are getting serialized with right pattern.
@Configuration
public class KafkaCustomizer implements DefaultKafkaProducerFactoryCustomizer {
@Bean
public ObjectMapper objectMapper() {
var mapper = new ObjectMapper();
var module = new JavaTimeModule();
var serializer = new LocalDateTimeSerializer(
DateTimeFormatter.ofPattern(DateConstants.DATETIME_FORMAT_PATTERN));
module.addSerializer(LocalDateTime.class, serializer);
mapper.registerModule(module);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return mapper;
}
@Override
public void customize(DefaultKafkaProducerFactory<?, ?> producerFactory) {
producerFactory.setValueSerializer(new JsonSerializer<>(objectMapper()));
}
}
But now I face another problem, the spring.kafka.producer.properties.spring.json.type.mapping
property is being ignored.
The __TypeId__
header of my record is set with FQCN and not with the token I have put in spring.json.type.mapping
property : foo > com.foo.package.Foo
When I did debbug it seems that the configure
method of org.springframework.kafka.support.serializer.JsonSerializer
class is not being invoked :
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
...
if (configs.containsKey(TYPE_MAPPINGS) && !this.typeMapperExplicitlySet
&& this.typeMapper instanceof AbstractJavaTypeMapper) {
((AbstractJavaTypeMapper) this.typeMapper)
.setIdClassMapping(createMappings((String) configs.get(TYPE_MAPPINGS)));
}
}
But when I disable the customization
@Override
public void customize(DefaultKafkaProducerFactory<?, ?> producerFactory) {
// producerFactory.setValueSerializer(new JsonSerializer<>(objectMapper()));
}
Then the __TypeId__
header is set with right token But as expected I loose the date format with my custom ObjectMapper
So how to handle this whole situation ?