# apigenie-generator server spring (AsyncAPI)

Source: https://apigenie.pl/docs/reference/generator/server-spring-asyncapi
Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md).
Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md).

[Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification)

Generate a Spring Boot application of the Kafka channels of an AsyncAPI document.

## Usage

```sh
apigenie-generator server spring [...OPTIONS] INPUT_FILE
```

## Description

`apigenie-generator server spring` generates from OpenAPI documents (see
[`apigenie-generator server spring`](/docs/reference/generator/server-spring)) and from AsyncAPI 3.x
documents, telling them apart by their `openapi` or `asyncapi` field. Documents referencing other
files are bundled first.

From an AsyncAPI document it generates a Maven project of a Spring Boot 3 application using
[Spring for Apache Kafka](https://spring.io/projects/spring-kafka). By default the application
is the one the document describes: it sends the messages of `send` operations and receives the
messages of `receive` operations. Set the `perspective` option to `counterpart` to swap them.

The generator has one part per protocol. Today it generates the Kafka channels: the channels of
servers with the `kafka` or `kafka-secure` protocol, and channels with a Kafka binding in
documents without servers. Channels of other protocols are skipped and reported as info.

```java
@Component
class LabelFarm implements RequestLabelRenderHandler {
    @Override
    public RequestLabelRenderReply onRenderLabel(RenderLabel message) {
        LabelRenderResult result = render(message.payload());
        return new LabelRendered(message.key(), result, new LabelRenderedHeaders(null));
    }
}

@Service
class Shipments {
    private final PublishShipmentEventsSender events;

    void delivered(String shipmentId, ShipmentDeliveredData data, ShipmentDeliveredHeaders headers) {
        events.sendShipmentDelivered(new ShipmentDelivered(shipmentId, data, headers));
    }
}
```

The generated code has:

- **models** (package `model`): a record per object schema the messages use, with Jackson and
  Jakarta Bean Validation annotations (`@NotNull` for required properties, `@Valid`, `@Pattern`,
  `@Size`, `@Min`/`@Max`, `@DecimalMin`/`@DecimalMax`, `@Email`); an enum per enumeration; a sealed
  interface per `oneOf` of objects (`@JsonTypeInfo` by the `discriminator` property, or by
  deduction). `allOf` members are merged into one record. Schemas under
  `#/components/schemas` keep their name; inline schemas are named after their message
  (`PlaceOrderPayload`) or their owner and property (`LabelRenderRequestFormat`).
- **messages** (package `messages`): a record per message with its Kafka `key`, its `payload` and
  its `headers`, and a headers record with the message's headers, the headers of its traits
  merged as AsyncAPI does (JSON Merge Patch: a later `required` list replaces an earlier one).
  Headers with a constant value, e.g. the `ce_specversion` and `ce_type` of CloudEvents in binary
  mode, are constants of the headers record (`ShipmentStatusChangedHeaders.CE_TYPE`), which
  senders write and listeners compare. The key is a `String` validated by the key schema of the
  Kafka message binding.
- **Kafka** (package `kafka`):
  - for every received operation, a handler interface (`ConsumeOrdersHandler`) with an
    `on<Message>` method per message, which you implement as a Spring bean, and a listener
    (`ConsumeOrdersListener`) with a `@KafkaListener` method. Several messages of a channel are
    told apart by a payload property or a header with a distinct constant value (e.g. `type` or
    `ce_type`); otherwise the first message whose payload is valid is chosen. Records matching no
    message go to `onUnknown`, which ignores them by default.
  - for every sent operation, a sender (`PublishShipmentEventsSender`) with a
    `send<Message>(message)` method per message, over a `KafkaTemplate` using the operation's
    client id.
  - request/reply operations with a reply channel: the requester's sender uses a
    `ReplyingKafkaTemplate` listening on the reply channel's topic and returns
    `CompletableFuture<<Operation>Reply>`, a sealed interface of the reply messages. Replies are
    matched by the header of the request message's `correlationId`, generated when the request
    has none. A replier's handler returns the reply, which the listener sends to the reply topic
    with the request's correlation id copied (from a header or a payload property, as the
    `correlationId` locations say).
  - `KafkaJson`, converting payloads (JSON) and headers (UTF-8 text) and validating messages, and
    `KafkaTopicsConfiguration`, creating the topics of the channels from their Kafka bindings
    (partitions, replicas, `topicConfiguration`) when `asyncapi.kafka.create-topics` is `true`.
- **project files**: `pom.xml` (parent `spring-boot-starter-parent`, `spring-boot-starter`,
  `spring-boot-starter-json`, `spring-boot-starter-validation` (with `bean_validation`),
  `spring-kafka`, and the test
  starters), the `@SpringBootApplication` class and `src/main/resources/application.yaml`.

`application.yaml` points `spring.kafka.bootstrap-servers` to the first Kafka server (server
variables replaced by their default) and configures String keys and byte array values. The
`asyncapi.kafka` section holds every Kafka server, the topic of every channel and the group and
client ids of every operation, which the generated code reads, so that they can be changed without
regenerating:

```yaml
asyncapi:
  kafka:
    create-topics: false
    servers:
      production-kafka:
        bootstrap-servers: kafka-eu.events.carpetexpress.example:9093
        schema-registry-url: https://schemas.events.carpetexpress.example
    channels:
      shipment-events:
        topic: carpetexpress.shipment-events.v2
    operations:
      consume-carrier-scans:
        group-id: tracking-ingest
        client-id: carpet-express-consume-carrier-scans
```

### Security

Each SASL or client certificate scheme of the Kafka servers gets a Spring profile named after its
key in kebab case, e.g. `kafka-scram` for `kafkaScram`, as a document of `application.yaml`. Start
the application with the profile (`--spring.profiles.active=kafka-scram`) to connect with the
scheme; without one, it connects without security. The credentials come from environment
variables named after the scheme key, e.g. `KAFKA_SCRAM_USERNAME` and `KAFKA_SCRAM_PASSWORD`:

| Scheme | Profile settings |
| ------ | ---------------- |
| `scramSha256`, `scramSha512` | `spring.kafka.security.protocol` `SASL_SSL` (`SASL_PLAINTEXT` on `kafka` servers), `sasl.mechanism` and a `ScramLoginModule` `sasl.jaas.config` with `<KEY>_USERNAME` and `<KEY>_PASSWORD` |
| `plain`, `userPassword` | the same with `PLAIN` and `PlainLoginModule` |
| `X509` | `spring.kafka.security.protocol` `SSL` and an SSL bundle (`spring.kafka.ssl.bundle`) of the PEM files `<KEY>_CERT` (the client certificate), `<KEY>_KEY` (its private key) and `<KEY>_CA` |

A scheme shared by servers with different protocols gets one profile, with the protocol of the
first of them, and a warning names both servers.

```yaml
---
spring:
  config:
    activate:
      on-profile: kafka-scram
  kafka:
    security:
      protocol: SASL_SSL
    properties:
      sasl.mechanism: SCRAM-SHA-512
      sasl.jaas.config: org.apache.kafka.common.security.scram.ScramLoginModule required username="${KAFKA_SCRAM_USERNAME}" password="${KAFKA_SCRAM_PASSWORD}";
```

Other scheme types, such as `gssapi`, are left out with a warning.

### Avro payloads

A message whose `schemaFormat` is an Avro one (`application/vnd.apache.avro;version=1.9.0`, with
or without `+json` or `+yaml`) carries the Avro class of its record schema as its payload. The
schema is written to `src/main/avro/<full name>.avsc` and the `avro-maven-plugin` generates the
class (strings as `String`) when the project builds. A schema without a `namespace` gets
`<base package>.avro`; a root schema that isn't a record is skipped with a warning.

The generated `KafkaAvro` bean encodes and decodes the payloads in Avro's binary encoding, with
the id of the writer's schema where the Kafka binding of the message says: before the payload
(`schemaIdLocation: payload`, Confluent's wire format) or in the `apicurio.value.globalId`
header (`schemaIdLocation: header`). Senders get the id from a schema registry, by the subject
of `schemaLookupStrategy` (`TopicIdStrategy`, `{topic}-value`, by default):

- a `KafkaAvro.SchemaRegistry` bean, when the application defines one;
- otherwise the Confluent-compatible registry at the `schema-registry-url` of the first Kafka
  server, with the basic authentication of `asyncapi.kafka.schema-registry.username` and
  `password`. It registers each schema once with `POST /subjects/{subject}/versions`.

```java
@Bean
KafkaAvro.SchemaRegistry schemaRegistry() {
    return KafkaAvro.confluent("https://schemas.events.carpetexpress.example", "ingest", System.getenv("REGISTRY_PASSWORD"));
}
```

Listeners decode records with the schema of the generated class, so the writer's schema must be
the same. A record that isn't a payload of it fails with an `IllegalArgumentException`, or goes to
`onUnknown` when the channel has several messages. A correlation id at a payload
pointer of an Avro message is left out with a warning.

Group and client ids come from the `groupId` and `clientId` schemas of the Kafka operation
bindings, of the operation or its traits: their `const`, single `enum` value, `default` or first
example. Without a value, `<artifact id>-<operation>` is used, with a comment naming the
binding's pattern.

Constraints Bean Validation can't express are line comments of the record or component: draft-07
`dependencies`, `if`/`then`/`else`, `not`, tuples (`items` arrays, mapped to `List` with `@Size`),
`patternProperties`, `const` values, and `anyOf`/`oneOf` branches constraining the properties of
an object.

Not supported, and reported as warnings: payloads of non-JSON schema formats other than Avro
(Protobuf, RAML) (the messages are skipped, and operations left without a message too), reply
addresses given by runtime expressions, Kafka topics with parameters, and security schemes other
than `plain`, `scramSha256`, `scramSha512`, `userPassword` and `X509` (such as `gssapi`). With a
correlation id in the payload, the replier's reply must carry the property (the listener overwrites
it with the request's), and a requester matches replies by the `kafka_correlationId` header, which
the replier must copy.

## Extensions

| Extension | Effect |
| --------- | ------ |
| `x-apigenie.codegen.name` | name of the class of a schema |
| `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) |

The extensions can live in an overlay for this target instead of in the document, e.g.
`spring.overlay.yaml`:

```yaml
overlay: 1.0.0
info:
  title: Java names
  version: 1.0.0
actions:
  - target: $.components.schemas.Order
    update:
      x-apigenie:
        codegen:
          name: PurchaseOrder
```

```sh
apigenie-generator server spring asyncapi.yaml --overlay spring.overlay.yaml -o out
```

## Options

### -c, --config

Path to the configuration file to use. See the "Configuration" section for more information.

### --overlay OVERLAY

Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the
extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those
listed under `commands.generate.server_spring.overlay` in the configuration file (with paths
relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays
apply to the AsyncAPI document bundled with the files it references.

### --strict

Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated)
instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`).

### --check

Writes nothing: compares what the generator would write with the output directory, prints the
files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See
[Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date).

### -o, --output

Directory where the project is generated.

### --package-name

Maven artifact id of the project. Defaults to the title of the API in kebab case. The base package
defaults to `com.example.` followed by the artifact id in lower case without other characters than
letters and digits (prefixed with `app` when it starts with a digit or is a Java keyword).

### --package-version

Version of the project. Defaults to the version of the API.

### -p, --property

Applies to OpenAPI documents only; using it with an AsyncAPI document is an error.

## Configuration

The options are read from the `asyncapi` section of the configuration of `apigenie-generator server spring`;
its other keys configure the generation from OpenAPI documents.

```yaml
version: '1.0'
commands:
  generate:
    server_spring:
      asyncapi:
        base_package: com.acme.events
        group_id: com.acme
        java_version: 21
        spring_boot_version: 3.3.13
        bean_validation: true
        perspective: application
```

| Option | Description |
| ------ | ----------- |
| `base_package` | Package of the generated code (default: `com.example.<artifact id>`); models are in `.model`, messages in `.messages`, the Kafka code in `.kafka` |
| `group_id` | Maven group id (default: the base package) |
| `java_version` | Java release, 17 (default) or later |
| `spring_boot_version` | Version of the Spring Boot 3 parent (default `3.3.13`) |
| `bean_validation` | `true` (default): Bean Validation annotations, and validation of sent and received messages; `false`: none |
| `perspective` | `application` (default): the described application; `counterpart`: its counterpart, receiving what it sends |

## Verification

The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi).

This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives.

| Results | Level 1 | Level 2 | Level 3 |
| --- | --- | --- | --- |
| Release 0.12.0 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | ✓ 5 of 5 operations pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) |
| Development version | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release |
