Sub topic 3
Setting up Spring Boot with Spring for Apache Kafka
This chapter connects a Spring Boot application to a Kafka broker. It covers the dependency, a local broker, what Spring Boot configures for you, and how the spring.kafka.* properties map to Kafka client settings. Later chapters build the producer, the listener and the error handling on top of this setup.
Prerequisites
This chapter assumes you know:
- Java 17 or later and basic Spring Boot (beans, dependency injection,
application.yml). - Maven or Gradle dependency management.
- The Kafka vocabulary from the first two chapters: broker, topic, partition, offset, consumer group.
- How to start a container with Docker.
What Spring for Apache Kafka adds
The plain Kafka client library gives you KafkaProducer and KafkaConsumer. You must create them, configure them and run the consumer poll loop yourself. Spring for Apache Kafka (the spring-kafka library) wraps these clients with:
KafkaTemplate, a thread-safe producer facade.@KafkaListener, an annotation that runs a poll loop on your behalf and calls your method for each record.- Listener containers, the objects that own the consumer, its threads and its error handling.
KafkaAdmin, which creates topics declared as beans.
Spring Boot's auto-configuration builds all of these from spring.kafka.* properties. In most applications you write no configuration classes for the basic setup.
Adding the dependency
Spring Boot manages the spring-kafka version, so you do not specify one. With Maven:
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>With Gradle:
implementation 'org.springframework.kafka:spring-kafka'The starter pulls in kafka-clients transitively, and the JSON support uses the Jackson library that Spring Boot already provides. The test library spring-kafka-test is a separate dependency, covered in the testing chapter.
Running a local broker
The Kafka project publishes an apache/kafka Docker image that runs a single broker in KRaft mode (no ZooKeeper). Its defaults listen on localhost:9092, which matches the configuration below.
services:
kafka:
image: apache/kafka:3.9.0
ports:
- "9092:9092"Save this as compose.yaml and run docker compose up -d. A single broker is enough for learning. It also explains why the topic in this tutorial uses replicas(1): a topic cannot have more replicas than there are brokers.
What auto-configuration creates
When spring-kafka is on the classpath, Spring Boot's KafkaAutoConfiguration reads the spring.kafka.* properties into a KafkaProperties object and registers these beans:
| Bean | Role |
|---|---|
| `ProducerFactory` | Creates the underlying Kafka producer from `spring.kafka.producer.*` |
| `KafkaTemplate` | The sending API, built on the producer factory |
| `ConsumerFactory` | Creates Kafka consumers from `spring.kafka.consumer.*` |
| `ConcurrentKafkaListenerContainerFactory` | Builds the containers that run `@KafkaListener` methods |
| `KafkaAdmin` | Talks to the broker and creates `NewTopic` beans at startup |
Boot also enables @KafkaListener processing for you, so you do not add @EnableKafka yourself.
Configuring the connection
This is the complete configuration used throughout the tutorial.
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
acks: all
properties:
enable.idempotence: true
consumer:
group-id: order-service
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
spring.json.trusted.packages: com.example.orders
spring.json.value.default.type: com.example.orders.OrderEventEach property maps to a Kafka client setting:
| Spring property | Kafka client setting | Purpose |
|---|---|---|
| `bootstrap-servers` | `bootstrap.servers` | Initial brokers the client contacts to discover the cluster |
| `producer.key-serializer` | `key.serializer` | Converts the key object to bytes |
| `producer.value-serializer` | `value.serializer` | Converts the value object to bytes |
| `producer.acks` | `acks` | How many replicas must confirm a write |
| `consumer.group-id` | `group.id` | The consumer group this application joins |
| `consumer.auto-offset-reset` | `auto.offset.reset` | Where to start when the group has no committed offset |
| `consumer.key-deserializer` | `key.deserializer` | Converts key bytes to an object |
| `consumer.value-deserializer` | `value.deserializer` | Converts value bytes to an object |
Settings without a dedicated property
KafkaProperties exposes only the common settings as named properties. Anything else goes under producer.properties, consumer.properties or the shared spring.kafka.properties. Keys in these maps use the raw Kafka names. That is why enable.idempotence and the spring.json.* settings appear under properties. Spring Boot passes them to the client unchanged.
You can list several brokers, separated by commas:
spring:
kafka:
bootstrap-servers: broker1:9092,broker2:9092,broker3:9092The client needs only one reachable address to discover the rest of the cluster. Listing more than one protects the initial connection if one broker is down.
Properties worth understanding now
auto-offset-resetapplies only when the consumer group has no committed offset for a partition. Withearliest, a new group reads from the start of the topic. With the defaultlatest, it sees only records sent after it joins. Once the group has committed offsets, the setting has no effect, which surprises people who change it and see no change.group-idis required for a subscribing consumer. If neither the property nor the@KafkaListenergroupIdattribute sets one, the consumer fails at startup.spring.json.trusted.packageslimits which classes theJsonDeserializeris allowed to instantiate. Without it, deserialization fails for classes outsidejava.utilandjava.lang. Avoid the wildcard*in production, because it lets a message choose which class to create.spring.json.value.default.typetells the deserializer which class to use when the record carries no type information in its headers.
Serialization has its own chapter, so treat these JSON settings as given for now.
Verifying the setup
A quick way to confirm that the YAML reached the client is to read the producer factory's configuration at startup. Create the application class and a runner:
package com.example.orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.core.KafkaTemplate;
@SpringBootApplication
public class OrdersApplication {
private static final Logger log = LoggerFactory.getLogger(OrdersApplication.class);
public static void main(String[] args) {
SpringApplication.run(OrdersApplication.class, args);
}
@Bean
public ApplicationRunner showKafkaConfig(KafkaTemplate<String, OrderEvent> template) {
return args -> {
var config = template.getProducerFactory().getConfigurationProperties();
log.info("bootstrap.servers={}", config.get("bootstrap.servers"));
log.info("acks={}", config.get("acks"));
log.info("enable.idempotence={}", config.get("enable.idempotence"));
};
}
}This class uses the OrderEvent record defined in the serialization chapter:
package com.example.orders;
public record OrderEvent(String orderId, long amountCents) {}Start the application. The log should show bootstrap.servers=[localhost:9092], acks=all and enable.idempotence=true. The producer does not connect to the broker until the first send, so these lines prove only that the configuration is bound. When the application starts with a NewTopic bean, KafkaAdmin does contact the broker, and a wrong address shows up as a startup warning or error.
Overriding the defaults
Auto-configuration backs off when you define your own bean of the same type. If you declare a ProducerFactory or a ConcurrentKafkaListenerContainerFactory, Spring Boot uses yours and ignores the matching properties. Prefer properties first and add custom beans only for what the properties cannot express.
Some beans are picked up without replacing anything. Spring Boot's container factory configurer applies a single DefaultErrorHandler bean to the auto-configured listener containers. The error handling chapters use this to attach retries and dead-letter publishing.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Repeated `Connection to node -1 could not be established` warnings | Broker is not running, or `bootstrap-servers` is wrong | Start the broker and check the host and port |
| Connects to bootstrap, then fails on a different hostname | The broker advertises an address the client cannot resolve | Fix the broker's `advertised.listeners` so it matches how clients reach it |
| `IllegalArgumentException: The class '...' is not in the trusted packages` | The payload class is outside `spring.json.trusted.packages` | Add the package of the class |
| Listener starts but never receives old records | The group has committed offsets, or `auto-offset-reset` is `latest` | Use a new `group-id`, or reset the group's offsets |
| `No group.id` or `You must provide group.id` at startup | Consumer has no group | Set `spring.kafka.consumer.group-id` |
| `ClassCastException` or serializer errors when sending | The serializer does not match the value type | Match `value-serializer` to the object you send |
Environment-specific addresses
Keep the broker address out of the committed YAML where it differs per environment. Spring Boot's relaxed binding maps an environment variable to the property, so SPRING_KAFKA_BOOTSTRAP_SERVERS=broker1:9092 overrides spring.kafka.bootstrap-servers without a code change. Never place SASL credentials or keystore passwords in the file. Supply them through environment variables or a secrets store, using the spring.kafka.properties.* keys such as sasl.jaas.config.
Exercise
Your consumer group order-service already read the whole orders topic yesterday and committed its offsets. Today you change auto-offset-reset from latest to earliest and restart, expecting to re-read every record. Nothing is re-read. Why, and name two ways to get the behavior you wanted.
Show answer
auto-offset-reset applies only when the group has no committed offset for a partition (or the committed offset is out of range). The group committed offsets yesterday, so the consumer resumes from them and the setting is never consulted. To re-read the topic, either start the application with a new group-id, which has no committed offsets and so uses earliest, or reset the existing group's offsets to the beginning, for example with the kafka-consumer-groups.sh --reset-offsets --to-earliest tool while the group is stopped.
Exercise
You want the producer to use linger.ms=20, but spring.kafka.producer has no dedicated property for it. Where do you set it, and why does the key look different from the other producer properties?
Show answer
Put it under spring.kafka.producer.properties, as linger.ms: 20. Settings without a dedicated Spring property go into the properties map, and Spring Boot passes those keys to the Kafka client unchanged. The key uses the raw Kafka name with dots, unlike the kebab-case style of properties such as key-serializer, which Spring Boot translates to Kafka names itself.