Skip to content
Veltoryx Technologies
ProLesson 6.2Intermediate4 min readUpdated 31 October 2026

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:

java
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
    }
}
Spring @KafkaListener and ConcurrentMessageListenerContainer
Fig. 1 · Spring @KafkaListener and ConcurrentMessageListenerContainer

What Happens Behind the Annotation?

  1. Spring scans beans for @KafkaListener during startup.
  2. It registers a ConcurrentMessageListenerContainer powered by the auto-configured ConcurrentKafkaListenerContainerFactory.
  3. It spawns background listener threads that execute the native Kafka consumer poll() loop.
  4. Incoming byte payloads are automatically converted into your OrderEvent record using Jackson JSON message converters.
  5. Injected metadata parameters (@Payload, @Header) are populated using Spring's method argument resolvers.

Loading the rest of the lesson…