The Spring Kafka reference documentation suggest to create the beans for Kafka templates explicitly. I'm using spring-boot-starter 2.3.3 and spring-kafka 2.5.5 and I noticed that you can just create a producer factory with a wildcard type and the Kafka template beans are created automatically. The downside of this approach is that the IDE can no longer correctly evaluate whether an @Autowired Kafka template bean actually exists. The advantage is less configuration when you use a lot of different value types in Kafka templates.
Are there any other reasons I should define these beans explicitly?
// In a @Configuration class
// Variant: Just define a wildcard producer
@Bean
public ProducerFactory<String, ?> wildcardProducerFactory(){
return new DefaultKafkaProducerFactory<>(config, new StringSerializer(), new JsonSerializer<>());
}
// Variant: Define specific producer and template
@Bean
public ProducerFactory<String, Foo> fooProducerFactory(){
return new DefaultKafkaProducerFactory(config, new StringSerializer(), new JsonSerializer());
}
@Bean
public KafkaTemplate<String, Foo> fooKafkaTemplate(){
return new KafkaTemplate<>(fooProducerFactory());
}
// Somewhere in a @Component class
// Usage here is the same for both variants
@Autowired
private KafkaTemplate<String, Foo> fooKafkaTemplate;