liveBook · Manning

@KafkaHandler

As explained in Kafka Streams in Action, Second Edition

@KafkaHandler is a Spring Kafka annotation that marks a method for dispatching records by the type of their values.

@KafkaHandler marks a method inside a class-level @KafkaListener. Spring selects the method whose single parameter matches the consumed record value type. section 12.2.1

Use it with these constraints:

  • Annotate each candidate handler with @KafkaHandler. section 12.2.1
  • Give every handler exactly one parameter. section 12.2.1
  • Keep parameter types distinct so dispatch is unambiguous. section 12.2.1
  • Designate one fallback with isDefault = true when unknown value types need handling. section 12.2.1

Dispatching multiple record types

A class-level listener can route String, Long, and Double values to separate methods, while a default Object handler receives unmatched types. section 12.2.1

Listing 12.9 Class level KafkaListener requires method annotations
@Component
@KafkaListener(topics = "${loan.app.input.topic}", groupId =
    "${application.group}")                                   #1
public class NewLoanApplicationProcessorListenerClassLevel {

  @KafkaHandler                                               #2
  public void doProcessLoanApplication(LoanApplication loanApplication) {
      // Handle the loan application
  }

  @KafkaHandler(isDefault = true)                  #3
  public void handleUnknownObject(Object unknown) {
     // Handle the unknown object
  }

Inspect the minimal class-level listener: one LoanApplication handler and one default handler. section 12.2.1

How Kafka Streams in Action, Second Edition covers it

How deep it goes
Explains annotation placement, single-parameter signatures, type ambiguity, and default handling without descending into consumer internals.
Examples
Uses LoanApplication, String, Long, Double, and unknown-object handler methods as dispatch examples.
What it assumes
Assumes familiarity with @KafkaListener and Java method parameter types.
What you can do after
Operate/configure a class-level listener that dispatches multiple value types and catches unmatched values.
How it connects
Connects @KafkaHandler with @KafkaListener, Kafka consumers, topics, partitions, and value types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kafka Streams in Action, Second Edition. The section links point to the parts of the book it draws on.