Generate Spring Kafka clients
This guide generates Spring Kafka producer and consumer interfaces for the channels of an AsyncAPI contract, together with the payload models they use. The generated code is a contract: your application implements the interfaces and owns all Kafka runtime configuration.
Configure the execution
Client generation needs modelPackage, clientPackage and client settings
on a java or kotlin execution. clientType and clientContract default to
spring-kafka and interface, their only values; the examples set them
explicitly.
Maven:
<configuration>
<generatorName>kotlin</generatorName>
<inputSpec>${project.basedir}/src/main/resources/asyncapi.yaml</inputSpec>
<modelPackage>com.example.accounts.model</modelPackage>
<clientPackage>com.example.accounts.client</clientPackage>
<clientConfig>
<clientType>spring-kafka</clientType>
<clientContract>interface</clientContract>
</clientConfig>
</configuration>
Gradle (clientConfig is shared by all executions and is declared once):
asyncApiGenerator {
clientConfig {
clientType.set("spring-kafka")
clientContract.set("interface")
}
executions {
register("accounts") {
generatorName.set("kotlin")
inputSpec.set(file("src/main/resources/asyncapi.yaml"))
modelPackage.set("com.example.accounts.model")
clientPackage.set("com.example.accounts.client")
}
}
}
CLI:
asyncapi-gen \
--input-spec src/main/resources/asyncapi.yaml \
--generator-name kotlin \
--model-package com.example.accounts.model \
--client-package com.example.accounts.client \
--client-type spring-kafka \
--client-contract interface
Use generatorName java for Java interfaces and models.
What is generated
For each channel, the generator writes a producer interface to
<clientPackage>.producer and a consumer interface to
<clientPackage>.consumer, named after the channel, for example
AccountUpdatedProducer and AccountUpdatedConsumer. Each message of the
channel gets one method in each interface:
- Producer
send<Message>(payload, key, headers...)returnsCompletableFuture<RecordMetadata>. The generated default returns a future that fails withUnsupportedOperationExceptionuntil you override it. - Consumer
listen<Message>(payload, receivedTopic, receivedKey, headers...)has a no-op default. Override it and add@KafkaListenerto the implementation method. - Message headers become
@Headerparameters; required headers are non-null, optional headers are nullable. A Kafka key schema becomes the key parameter type. A header whose parameter name would bepayload,receivedTopic,receivedKey, ormessageKeyfails generation, because the method already declares those parameters. - An array payload is typed as a
Listof its item type, and anintegerpayload asLongforformat: int64or bounds outside the 32-bit range. A scalar payload gets the type the models give the same schema: a string withformatuuid,date, ordate-timeisUUID,LocalDate, orOffsetDateTime, anumberisDouble, and anumberwithmultipleOfisBigDecimal. This holds for the producer and the consumer method, in Kotlin and Java. - Each interface has a topic constant, such as
ACCOUNT_UPDATED_TOPIC_ADDRESS, holding the channel address.
Generation fails, naming the channel, when:
- a channel has no
address; - a channel declares no messages;
- two channel IDs become the same interface name after normalization, such as
account-eventsandaccount_events; or - two messages of one channel become the same method name.
Rename or complete the channel or message in the contract. These are listed with the other generation compatibility errors.
The interfaces do not create beans, register listeners, or configure brokers, serializers, consumer groups, retries, or transactions. The generated KDoc and Javadoc include an example implementation. The complete approved output for a sample contract is linked from Spring Kafka contracts with typed headers.
The application needs Spring Kafka on the compile classpath, plus the dependencies of the generated models (see Generate Kotlin and Java models).
Generate only producers or only consumers
Producer and consumer interfaces are both generated by default. AsyncAPI
operation actions (send, receive) do not select them; disable one category
explicitly:
| Frontend | Producers only |
|---|---|
| Maven | <consumer><enabled>false</enabled></consumer> in clientConfig |
| Gradle | consumer { enabled.set(false) } in clientConfig |
| CLI | --no-generate-consumer |
Disable producers the same way with producer or --no-generate-producer.
Disabling both fails.
Add methods for serialized payloads
additionalPayloadTypes adds producer methods that accept a payload your
application has already serialized, next to the typed method. The values are
byte-array and string:
| Frontend | Setting |
|---|---|
| Maven | <producer><additionalPayloadTypes><additionalPayloadType>byte-array</additionalPayloadType></additionalPayloadTypes></producer> |
| Gradle | producer { additionalPayloadTypes.set(listOf("byte-array", "string")) } |
| CLI | --producer-additional-payload-type byte-array (repeatable) |
Map channel parameters to Spring properties
A channel address such as accounts.{environment}.updated.v1 contains a
parameter. Map the parameter to a Spring property so the topic constant
becomes accounts.${kafka.environment}.updated.v1, which Spring resolves from
your application configuration:
| Frontend | Setting |
|---|---|
| Maven | <topicParameterProperties><environment>kafka.environment</environment></topicParameterProperties> in clientConfig |
| Gradle | topicParameterProperties.put("environment", "kafka.environment") in clientConfig |
| CLI | --topic-parameter-property environment=kafka.environment (repeatable) |
Write the property name without ${...}.
Add validation annotations
To validate payloads at the interface boundary, configure fully qualified
annotations. clientContract annotates each interface and payloadParameter
annotates the typed payload parameter of producer and consumer methods; it is
not applied to the additional byte-array and string producer methods:
<clientConfig>
<clientType>spring-kafka</clientType>
<clientContract>interface</clientContract>
<validationAnnotations>
<clientContract>org.springframework.validation.annotation.Validated</clientContract>
<payloadParameter>jakarta.validation.Valid</payloadParameter>
</validationAnnotations>
</clientConfig>
In Gradle use validationAnnotations { clientContract.set("...");
payloadParameter.set("...") } inside clientConfig; in the CLI use
--client-contract-validation-annotation and
--payload-parameter-validation-annotation. The application must enable
method validation for these annotations to take effect.
Share client settings across executions
Client settings in Gradle's clientConfig, or in Maven's plugin-level
configuration, reach every execution. Executions without clientPackage
ignore them and print the unused-client-config warning; silence it with
suppressedWarnings as described in
Configuration warnings.
All client settings and their validation rules are listed in the generator configuration reference.