为什么要明确定义KafkaTemplate bean?

问题描述

Spring Kafka reference documentation建议为Kafka模板显式创建bean。我使用的是spring-boot-starter 2.3.3和spring-kafka 2.5.5,我注意到您可以使用通配符类型创建生产者工厂,并且Kafka模板bean是自动创建的。这种方法的缺点是IDE不能再正确评估@Autowired Kafka模板bean是否确实存在。优点是,当您在Kafka模板中使用许多不同的值类型时,配置较少。

还有其他原因我应该明确定义这些bean吗?

    // 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 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;

解决方法

使用Spring Boot,甚至不需要创建ProducerFactory bean。自动配置会为您解决这一问题:https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-kafka

有关如何通过配置属性提供序列化器的更多信息,另请参见KafkaProperties.Producer

在注入bean时不考虑泛型:如果其根类型匹配,那么就很好了。无论如何,运行时都没有任何泛型-Java中的擦除类型。

您可能只是对IDE表示感到困惑。而且,由于这些bean未在您的项目中声明,因此它不会在运行时由Spring Boot在运行时显示的classpath中看到。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...