Consuming Messages with @KafkaListener
Master declarative consumption with @KafkaListener, configure container factory concurrency, extract headers, and control offset commit modes.
Writing a raw Java consumer requires writing infinite while-loops, catching wake-up interrupts, managing rebalance listeners, and handling thread interruptions manually.
Spring for Apache Kafka replaces this low-level boilerplate with @KafkaListener, a declarative annotation that turns any standard Spring bean method into an enterprise-grade message listener.
In this lesson, you will master @KafkaListener, understand how the underlying ConcurrentMessageListenerContainer achieves thread concurrency, extract metadata headers, and manage manual offset acknowledgments.
01Declarative Consumption with @KafkaListener
To consume messages from a topic, annotate a service method with @KafkaListener:
package com.veltoryx.kafka.consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;
@Service
public class OrderNotificationConsumer {
private static final Logger log = LoggerFactory.getLogger(OrderNotificationConsumer.class);
@KafkaListener(topics = "orders", groupId = "notification-service-group")
public void onOrderEvent(
@Payload OrderEvent event,
@Header(KafkaHeaders.RECEIVED_KEY) String key,
@Header(KafkaHeaders.RECEIVED_PARTITION) int partition,
@Header(KafkaHeaders.OFFSET) long offset) {
log.info("Received event for order [{}] from partition {} at offset {}",
key, partition, offset);
// Execute notification dispatch logic
sendNotification(event);
}
private void sendNotification(OrderEvent event) {
// Business logic execution
}
}What Happens Behind the Annotation?
- Spring scans beans for
@KafkaListenerduring startup. - It registers a
ConcurrentMessageListenerContainerpowered by the auto-configuredConcurrentKafkaListenerContainerFactory. - It spawns background listener threads that execute the native Kafka consumer
poll()loop. - Incoming byte payloads are automatically converted into your
OrderEventrecord using Jackson JSON message converters. - Injected metadata parameters (
@Payload,@Header) are populated using Spring's method argument resolvers.
Loading the rest of the lesson…