0
0
KafkaHow-ToBeginner · 3 min read

How to Use @KafkaListener in Spring Kafka

Use @KafkaListener on a method to make it listen to Kafka topic messages automatically. Annotate a Spring-managed bean method with @KafkaListener(topics = "topicName") to receive messages from that topic.
📐

Syntax

The @KafkaListener annotation is placed on a method to mark it as a message listener for Kafka topics. Key parts include:

  • topics: The Kafka topic(s) to listen to.
  • groupId: The consumer group id for the listener.
  • containerFactory: Optional, specifies the Kafka listener container factory bean.
java
@KafkaListener(topics = "myTopic", groupId = "myGroup")
public void listen(String message) {
    // process message
}
💻

Example

This example shows a Spring Boot application with a @KafkaListener method that listens to the topic testTopic and prints received messages.

java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class KafkaListenerExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(KafkaListenerExampleApplication.class, args);
    }
}

@Component
class MessageListener {
    @KafkaListener(topics = "testTopic", groupId = "group1")
    public void listen(String message) {
        System.out.println("Received message: " + message);
    }
}
Output
Received message: Hello Kafka Received message: Another message
⚠️

Common Pitfalls

Common mistakes when using @KafkaListener include:

  • Not setting groupId, causing consumer group conflicts.
  • Using incorrect topic names or missing topics.
  • Not configuring Kafka consumer properties properly in application.properties.
  • Placing @KafkaListener on non-Spring-managed beans.

Always ensure your listener method signature matches the message payload type.

java
/* Wrong: Missing groupId */
@KafkaListener(topics = "myTopic")
public void listen(String msg) {
    // ...
}

/* Right: Specify groupId */
@KafkaListener(topics = "myTopic", groupId = "myGroup")
public void listen(String msg) {
    // ...
}
📊

Quick Reference

PropertyDescription
topicsKafka topic(s) to listen to
groupIdConsumer group id for the listener
containerFactoryKafka listener container factory bean name (optional)
idUnique id for the listener (optional)
autoStartupWhether listener starts automatically (default true)

Key Takeaways

Annotate a Spring bean method with @KafkaListener to consume Kafka topic messages automatically.
Always specify the groupId to avoid consumer group conflicts.
Ensure your listener method parameter matches the message payload type.
Configure Kafka consumer properties correctly in your Spring application.
@KafkaListener methods must be in Spring-managed beans to work.