Spring Kafka KafkaListener注解是否可以将config 属性作为主题名?

Is Spring Kafka KafkaListener annotation able to take config property as topic name?

我有如下定义:

    @KafkaListener(
            topics = "${app.kafka.eventTopic}",
            groupId = "${app.kafka.consumerGroupId}",
            concurrency = "${app.kafka.concurrency}"
    )

我在我的 yaml 文件中定义了这些配置属性,例如:

app:
  kafka:
    eventTopic: topicName
    consumerGroupId: groupName
    concurrency: 10

我是 SpringBoot 的新手,我看到一些 SO 帖子声称像 ${app.kafka.eventTopic} 这样的语法不能像 @Value() 注释那样工作并且需要 ConfigurationProperties class 来“翻译" Java 变量的属性值。如果 @Value 注释是这样,那么这里对 KafkaListener 注释内容的工作方式是否相同?

这应该可以在正常的 spring 启动应用程序中运行,无需任何“翻译程序”。例如。只要相应的 属性 在您的 application.propertiesapplication.yaml:

中,这应该可以正常工作
@KafkaListener(
    topics = "${kafka.topics.consume.somedata}", 
    id = MyConsumer.CONTAINER_ID)

您甚至可以使用更高级的 SPeL 表达式,例如:

@KafkaListener(topics = "#{'${consumer.topics}'.split(',')}", ...)

您可以阅读有关 SpEL 的更多信息 here

实际上,Value 和 KafkaListener 注释的处理方式略有不同。一个由 AutowiredAnnotationBeanPostProcessor and the other by KafkaListenerAnnotationBeanPostProcessor.