Andi
Andi

Reputation: 700

Why explictly define KafkaTemplate beans?

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;

Upvotes: 4

Views: 4418

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121462

With Spring Boot you even don't need to create a ProducerFactory bean. The auto-configuration takes care about that for you: https://docs.spring.io/spring-boot/docs/current/reference/html/messaging.html#messaging.kafka

See also a KafkaProperties.Producer for more info how to provide serializers via configuration properties.

Generics are not taken into account when you inject a bean: if its root type match, then you are good to go. There is no any generics at runtime anyway - type erasure in Java.

You probably just confused by the IDE representation. And since those beans are not declared in your project, it doesn't see them from classpath where they are presented by Spring Boot at runtime.

Upvotes: 4

Related Questions