Video in progress
In Spring Kafka, what do you do when JSON messages from another service fail with a "class not found" or "not in trusted packages" error?
By default JsonSerializer writes the class name into the __TypeId__ header, and JsonDeserializer looks up the class by that name. The consumer doesn't have that package, or it isn't trusted. The fix is to give the target type explicitly instead of relying on the header, or to configure type mapping.
📖 Answer
The producer sends com.shop.order.OrderCreated, but the consumer has its own class, com.shop.billing.OrderCreatedEvent. The header carries the producer's class name, and the consumer can't find it.
The simplest way, and the one I prefer, is to ignore the header and set the type on the consumer:
spring:
kafka:
consumer:
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
spring.json.use.type.headers: false
spring.json.value.default.type: com.shop.billing.OrderCreatedEvent
If you also set spring.json.add.type.headers: false on the producer side, internal class names don't leak outside.
If one topic carries several event types, use type mapping: spring.json.type.mapping: orderCreated:com.shop.billing.OrderCreatedEvent, and give the same token on the producer.
Setting spring.json.trusted.packages: "*" looks like a quick fix, but it allows deserializing arbitrary classes. I'd rather not do it even on an internal network.
Sign up to mark studied questions and save your progress.