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

Time:12-18

I have the following definition:

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

And I defined these config properties in my yaml file like:

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

I am new to SpringBoot and I saw some SO posts that claim syntax like ${app.kafka.eventTopic} does not work as is for @Value() annotation and needs ConfigurationProperties class to "translate" the properties values to Java variables. If that's true for @Value annotation, does it work the same way here for KafkaListener annotation content?

CodePudding user response:

This should work in a normal spring boot application without any "translators". E.g. this should work fine as long as the corresponding property is in your application.properties or application.yaml:

@KafkaListener(
    topics = "${kafka.topics.consume.somedata}", 
    id = MyConsumer.CONTAINER_ID)

You can even use more advanced SPeL expressions, e.g.:

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

You can read more about SpEL here.

Under the hood indeed the Value and KafkaListener annotations are handled slightly differently. One by the AutowiredAnnotationBeanPostProcessor and the other by KafkaListenerAnnotationBeanPostProcessor.

  • Related