CQRS and Event Sourcing in Spring Boot: Building an Order Service with Axon Framework 5

Introduction

Modern distributed systems face a fundamental tension: optimising for writes and optimising for reads often require different data shapes, consistency guarantees, and scalability strategies. Command Query Responsibility Segregation (CQRS) resolves this by splitting your model into two sides — a command side that handles state-changing operations and a query side that serves read requests from a purpose-built read model.

Event Sourcing takes CQRS further by replacing the conventional "overwrite the row" approach to persistence with an append-only log of immutable domain events. Rather than storing the current account balance, you store the sequence of MoneyDeposited and MoneyWithdrawn events, then derive the balance on demand. This gives you a complete, auditable history out of the box, the ability to replay events to rebuild any projection you like, and a natural fit for event-driven microservices.

Axon Framework 5 (released in 2026 and requiring Java 21) is the production-grade choice for implementing CQRS and Event Sourcing in Java. It provides a command bus, event bus, event store, query bus, aggregate lifecycle management, and a rich testing API — all wired into Spring Boot automatically via auto-configuration.

In this tutorial we will build a complete Order Management service that walks through every layer of the architecture: defining commands and events as Java records, implementing an OrderAggregate driven by domain events, building a JPA-backed read projection, exposing a REST API via CommandGateway and QueryGateway, and testing every piece with AggregateTestFixture.


Prerequisites

  • Java 21+ — Axon Framework 5 requires Java 21 as its minimum runtime
  • Maven 3.9+
  • Spring Boot 3.3+
  • Familiarity with Spring Boot, JPA, and basic DDD concepts (aggregate, command, event)
  • Optionally: Axon Server for production event storage; we use the embedded JPA event store for local development

Project Setup

Create a new Spring Boot project with the following pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
             https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.5</version>
    </parent>

    <groupId>com.vimleshpandey.demo</groupId>
    <artifactId>order-service-cqrs</artifactId>
    <version>1.0.0</version>

    <properties>
        <java.version>21</java.version>
        <axon.version>5.3.2</axon.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- Axon Framework 5 -->
        <dependency>
            <groupId>org.axonframework</groupId>
            <artifactId>axon-spring-boot-starter</artifactId>
            <version>${axon.version}</version>
            <exclusions>
                <!-- Disable Axon Server connector; use embedded event store locally -->
                <exclusion>
                    <groupId>org.axonframework</groupId>
                    <artifactId>axon-server-connector</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.axonframework</groupId>
            <artifactId>axon-test</artifactId>
            <version>${axon.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Create src/main/resources/application.yml:

spring:
  datasource:
    url: jdbc:h2:mem:orderdb;DB_CLOSE_DELAY=-1
    driver-class-name: org.h2.Driver
  jpa:
    hibernate:
      ddl-auto: create-drop
    show-sql: false
  h2:
    console:
      enabled: true

axon:
  axonserver:
    enabled: false   # embedded in-memory JPA event store for local dev

The axon.axonserver.enabled: false property switches Axon to its in-process JPA-backed event store — perfect for development and integration tests.


Domain Model: Commands and Events

CQRS starts with drawing a clear boundary between commands (things you want to happen) and events (things that did happen). Java records are ideal for both — they are immutable value objects with built-in equals, hashCode, and toString.

// src/main/java/com/vimleshpandey/demo/order/api/OrderItem.java
package com.vimleshpandey.demo.order.api;

import java.math.BigDecimal;

public record OrderItem(String sku, int quantity, BigDecimal unitPrice) {
    public OrderItem {
        if (quantity <= 0) throw new IllegalArgumentException("Quantity must be positive");
        if (unitPrice.compareTo(BigDecimal.ZERO) <= 0)
            throw new IllegalArgumentException("Unit price must be positive");
    }
}
// src/main/java/com/vimleshpandey/demo/order/api/OrderStatus.java
package com.vimleshpandey.demo.order.api;

public enum OrderStatus { PLACED, CONFIRMED, SHIPPED, CANCELLED }
// src/main/java/com/vimleshpandey/demo/order/api/Commands.java
package com.vimleshpandey.demo.order.api;

import org.axonframework.modelling.command.TargetAggregateIdentifier;
import java.util.List;

public final class Commands {
    private Commands() {}

    public record PlaceOrderCommand(
        @TargetAggregateIdentifier String orderId,
        String customerId,
        List<OrderItem> items) {}

    public record ConfirmOrderCommand(
        @TargetAggregateIdentifier String orderId) {}

    public record ShipOrderCommand(
        @TargetAggregateIdentifier String orderId,
        String trackingNumber) {}

    public record CancelOrderCommand(
        @TargetAggregateIdentifier String orderId,
        String reason) {}
}

The @TargetAggregateIdentifier annotation tells Axon which field carries the aggregate ID, enabling the command bus to route each command to the correct aggregate instance.

// src/main/java/com/vimleshpandey/demo/order/api/Events.java
package com.vimleshpandey.demo.order.api;

import java.time.Instant;
import java.util.List;

public final class Events {
    private Events() {}

    public record OrderPlacedEvent(
        String orderId, String customerId, List<OrderItem> items, Instant placedAt) {}

    public record OrderConfirmedEvent(String orderId, Instant confirmedAt) {}

    public record OrderShippedEvent(String orderId, String trackingNumber, Instant shippedAt) {}

    public record OrderCancelledEvent(String orderId, String reason, Instant cancelledAt) {}
}

Implementing the OrderAggregate

The aggregate is the heart of the command side. In Axon Framework 5, the annotation changed: event-sourced aggregates use @Aggregate from org.axonframework.spring.stereotype, but the internal behaviour shifted significantly. The two key Axon 5 changes from version 4 are:

  1. EventAppender replaces AggregateLifecycle.apply() — event publication is now explicit in the command handler method signature rather than a static side-effect call.
  2. Static factory methods with @EntityCreator replace constructor-based creation command handlers.
// src/main/java/com/vimleshpandey/demo/order/command/OrderAggregate.java
package com.vimleshpandey.demo.order.command;

import com.vimleshpandey.demo.order.api.Commands.*;
import com.vimleshpandey.demo.order.api.Events.*;
import com.vimleshpandey.demo.order.api.OrderItem;
import com.vimleshpandey.demo.order.api.OrderStatus;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.eventsourcing.eventstore.EventAppender;
import org.axonframework.modelling.command.AggregateIdentifier;
import org.axonframework.modelling.command.EntityCreator;
import org.axonframework.spring.stereotype.Aggregate;

import java.time.Instant;
import java.util.List;

@Aggregate
public class OrderAggregate {

    @AggregateIdentifier
    private String orderId;
    private String customerId;
    private List<OrderItem> items;
    private OrderStatus status;

    protected OrderAggregate() {
        // Required by Axon for reconstitution from the event store
    }

    // ----------------------------------------------------------------
    // Creation command: static factory with @EntityCreator (Axon 5)
    // ----------------------------------------------------------------

    @CommandHandler
    @EntityCreator
    public static OrderAggregate handle(PlaceOrderCommand cmd, EventAppender events) {
        if (cmd.items() == null || cmd.items().isEmpty()) {
            throw new IllegalArgumentException("Order must contain at least one item");
        }
        events.append(new OrderPlacedEvent(
            cmd.orderId(),
            cmd.customerId(),
            List.copyOf(cmd.items()),
            Instant.now()
        ));
        return new OrderAggregate();
    }

    // ----------------------------------------------------------------
    // Lifecycle commands
    // ----------------------------------------------------------------

    @CommandHandler
    public void handle(ConfirmOrderCommand cmd, EventAppender events) {
        if (status != OrderStatus.PLACED) {
            throw new IllegalStateException("Cannot confirm order in status: " + status);
        }
        events.append(new OrderConfirmedEvent(cmd.orderId(), Instant.now()));
    }

    @CommandHandler
    public void handle(ShipOrderCommand cmd, EventAppender events) {
        if (status != OrderStatus.CONFIRMED) {
            throw new IllegalStateException("Cannot ship order in status: " + status);
        }
        events.append(new OrderShippedEvent(cmd.orderId(), cmd.trackingNumber(), Instant.now()));
    }

    @CommandHandler
    public void handle(CancelOrderCommand cmd, EventAppender events) {
        if (status == OrderStatus.SHIPPED || status == OrderStatus.CANCELLED) {
            throw new IllegalStateException("Cannot cancel order in status: " + status);
        }
        events.append(new OrderCancelledEvent(cmd.orderId(), cmd.reason(), Instant.now()));
    }

    // ----------------------------------------------------------------
    // Event sourcing handlers — rebuild state from events (no logic here)
    // ----------------------------------------------------------------

    @EventSourcingHandler
    public void on(OrderPlacedEvent event) {
        this.orderId = event.orderId();
        this.customerId = event.customerId();
        this.items = event.items();
        this.status = OrderStatus.PLACED;
    }

    @EventSourcingHandler
    public void on(OrderConfirmedEvent event) {
        this.status = OrderStatus.CONFIRMED;
    }

    @EventSourcingHandler
    public void on(OrderShippedEvent event) {
        this.status = OrderStatus.SHIPPED;
    }

    @EventSourcingHandler
    public void on(OrderCancelledEvent event) {
        this.status = OrderStatus.CANCELLED;
    }
}

Notice that @EventSourcingHandler methods contain no business logic — they only assign fields. All validation and rules live in the @CommandHandler methods. This separation is not just convention: Axon replays event sourcing handlers when loading an aggregate from the event store, so any logic there would execute on every load.


Building the Read Model (Projections)

The query side lives in OrderProjection. It listens for domain events over the event bus and maintains a denormalised JPA view optimised for reads — completely independent of the aggregate's internal state.

// src/main/java/com/vimleshpandey/demo/order/query/OrderView.java
package com.vimleshpandey.demo.order.query;

import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.Instant;

@Entity
@Table(name = "order_views")
public class OrderView {

    @Id
    private String orderId;
    private String customerId;
    private String status;
    private BigDecimal totalAmount;
    private Instant placedAt;
    private Instant confirmedAt;
    private Instant shippedAt;
    private Instant cancelledAt;
    private String trackingNumber;
    private String cancellationReason;

    // Getters and setters
    public String getOrderId() { return orderId; }
    public void setOrderId(String orderId) { this.orderId = orderId; }
    public String getCustomerId() { return customerId; }
    public void setCustomerId(String customerId) { this.customerId = customerId; }
    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }
    public BigDecimal getTotalAmount() { return totalAmount; }
    public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }
    public Instant getPlacedAt() { return placedAt; }
    public void setPlacedAt(Instant placedAt) { this.placedAt = placedAt; }
    public Instant getConfirmedAt() { return confirmedAt; }
    public void setConfirmedAt(Instant confirmedAt) { this.confirmedAt = confirmedAt; }
    public Instant getShippedAt() { return shippedAt; }
    public void setShippedAt(Instant shippedAt) { this.shippedAt = shippedAt; }
    public Instant getCancelledAt() { return cancelledAt; }
    public void setCancelledAt(Instant cancelledAt) { this.cancelledAt = cancelledAt; }
    public String getTrackingNumber() { return trackingNumber; }
    public void setTrackingNumber(String trackingNumber) { this.trackingNumber = trackingNumber; }
    public String getCancellationReason() { return cancellationReason; }
    public void setCancellationReason(String reason) { this.cancellationReason = reason; }
}
// src/main/java/com/vimleshpandey/demo/order/query/OrderViewRepository.java
package com.vimleshpandey.demo.order.query;

import org.springframework.data.jpa.repository.JpaRepository;

public interface OrderViewRepository extends JpaRepository<OrderView, String> {}
// src/main/java/com/vimleshpandey/demo/order/query/Queries.java
package com.vimleshpandey.demo.order.query;

public final class Queries {
    private Queries() {}
    public record FindOrderQuery(String orderId) {}
    public record FindAllOrdersQuery() {}
}
// src/main/java/com/vimleshpandey/demo/order/query/OrderProjection.java
package com.vimleshpandey.demo.order.query;

import com.vimleshpandey.demo.order.api.Events.*;
import com.vimleshpandey.demo.order.query.Queries.*;
import org.axonframework.eventhandling.EventHandler;
import org.axonframework.queryhandling.QueryHandler;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.NoSuchElementException;

@Component
public class OrderProjection {

    private final OrderViewRepository repository;

    public OrderProjection(OrderViewRepository repository) {
        this.repository = repository;
    }

    @EventHandler
    public void on(OrderPlacedEvent event) {
        OrderView view = new OrderView();
        view.setOrderId(event.orderId());
        view.setCustomerId(event.customerId());
        view.setStatus("PLACED");
        view.setPlacedAt(event.placedAt());
        BigDecimal total = event.items().stream()
            .map(item -> item.unitPrice().multiply(BigDecimal.valueOf(item.quantity())))
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        view.setTotalAmount(total);
        repository.save(view);
    }

    @EventHandler
    public void on(OrderConfirmedEvent event) {
        repository.findById(event.orderId()).ifPresent(v -> {
            v.setStatus("CONFIRMED");
            v.setConfirmedAt(event.confirmedAt());
            repository.save(v);
        });
    }

    @EventHandler
    public void on(OrderShippedEvent event) {
        repository.findById(event.orderId()).ifPresent(v -> {
            v.setStatus("SHIPPED");
            v.setShippedAt(event.shippedAt());
            v.setTrackingNumber(event.trackingNumber());
            repository.save(v);
        });
    }

    @EventHandler
    public void on(OrderCancelledEvent event) {
        repository.findById(event.orderId()).ifPresent(v -> {
            v.setStatus("CANCELLED");
            v.setCancelledAt(event.cancelledAt());
            v.setCancellationReason(event.reason());
            repository.save(v);
        });
    }

    @QueryHandler
    public OrderView handle(FindOrderQuery query) {
        return repository.findById(query.orderId())
            .orElseThrow(() -> new NoSuchElementException("Order not found: " + query.orderId()));
    }

    @QueryHandler
    public List<OrderView> handle(FindAllOrdersQuery query) {
        return repository.findAll();
    }
}

Projection handlers are idempotent by design: they use save() on a JPA entity with a known primary key. If Axon replays events (e.g., after a schema migration or a projection bug fix), re-applying the same event updates the existing row rather than creating a duplicate.


REST API

The controller decouples HTTP from the domain by going through CommandGateway and QueryGateway. Both are non-blocking and return CompletableFuture:

// src/main/java/com/vimleshpandey/demo/order/OrderController.java
package com.vimleshpandey.demo.order;

import com.vimleshpandey.demo.order.api.Commands.*;
import com.vimleshpandey.demo.order.api.OrderItem;
import com.vimleshpandey.demo.order.query.OrderView;
import com.vimleshpandey.demo.order.query.Queries.*;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.messaging.responsetypes.ResponseTypes;
import org.axonframework.queryhandling.QueryGateway;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private final CommandGateway commandGateway;
    private final QueryGateway queryGateway;

    public OrderController(CommandGateway commandGateway, QueryGateway queryGateway) {
        this.commandGateway = commandGateway;
        this.queryGateway = queryGateway;
    }

    @PostMapping
    public CompletableFuture<ResponseEntity<String>> placeOrder(
            @RequestBody PlaceOrderRequest request) {
        String orderId = UUID.randomUUID().toString();
        return commandGateway
            .send(new PlaceOrderCommand(orderId, request.customerId(), request.items()))
            .thenApply(result -> ResponseEntity.ok(orderId));
    }

    @PutMapping("/{orderId}/confirm")
    public CompletableFuture<Void> confirmOrder(@PathVariable String orderId) {
        return commandGateway.send(new ConfirmOrderCommand(orderId));
    }

    @PutMapping("/{orderId}/ship")
    public CompletableFuture<Void> shipOrder(
            @PathVariable String orderId,
            @RequestParam String trackingNumber) {
        return commandGateway.send(new ShipOrderCommand(orderId, trackingNumber));
    }

    @PutMapping("/{orderId}/cancel")
    public CompletableFuture<Void> cancelOrder(
            @PathVariable String orderId,
            @RequestParam String reason) {
        return commandGateway.send(new CancelOrderCommand(orderId, reason));
    }

    @GetMapping("/{orderId}")
    public CompletableFuture<OrderView> getOrder(@PathVariable String orderId) {
        return queryGateway.query(
            new FindOrderQuery(orderId),
            ResponseTypes.instanceOf(OrderView.class));
    }

    @GetMapping
    public CompletableFuture<List<OrderView>> getAllOrders() {
        return queryGateway.query(
            new FindAllOrdersQuery(),
            ResponseTypes.multipleInstancesOf(OrderView.class));
    }

    public record PlaceOrderRequest(String customerId, List<OrderItem> items) {}
}

Testing with Axon's AggregateTestFixture

Axon's AggregateTestFixture gives you a fluent, BDD-style DSL for testing aggregates in complete isolation — no Spring context, no event store, no database:

// src/test/java/com/vimleshpandey/demo/order/command/OrderAggregateTest.java
package com.vimleshpandey.demo.order.command;

import com.vimleshpandey.demo.order.api.Commands.*;
import com.vimleshpandey.demo.order.api.Events.*;
import com.vimleshpandey.demo.order.api.OrderItem;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

class OrderAggregateTest {

    private FixtureConfiguration<OrderAggregate> fixture;

    @BeforeEach
    void setUp() {
        fixture = new AggregateTestFixture<>(OrderAggregate.class);
    }

    @Test
    void shouldPublishOrderPlacedEventWhenOrderIsPlaced() {
        List<OrderItem> items = List.of(
            new OrderItem("SKU-001", 2, BigDecimal.valueOf(49.99)));

        fixture.givenNoPriorActivity()
            .when(new PlaceOrderCommand("order-1", "customer-1", items))
            .expectSuccessfulHandlerExecution()
            .expectEventsMatching(events -> {
                assertThat(events).hasSize(1);
                assertThat(events.get(0).getPayload())
                    .isInstanceOf(OrderPlacedEvent.class);
                OrderPlacedEvent event = (OrderPlacedEvent) events.get(0).getPayload();
                assertThat(event.orderId()).isEqualTo("order-1");
                assertThat(event.customerId()).isEqualTo("customer-1");
                return true;
            });
    }

    @Test
    void shouldConfirmPlacedOrder() {
        List<OrderItem> items = List.of(new OrderItem("SKU-001", 1, BigDecimal.TEN));
        OrderPlacedEvent placed =
            new OrderPlacedEvent("order-1", "customer-1", items, Instant.now());

        fixture.given(placed)
            .when(new ConfirmOrderCommand("order-1"))
            .expectSuccessfulHandlerExecution()
            .expectEventsMatching(events -> {
                assertThat(events).hasSize(1);
                assertThat(events.get(0).getPayload())
                    .isInstanceOf(OrderConfirmedEvent.class);
                return true;
            });
    }

    @Test
    void shouldRejectConfirmationIfOrderAlreadyConfirmed() {
        List<OrderItem> items = List.of(new OrderItem("SKU-001", 1, BigDecimal.TEN));
        OrderPlacedEvent placed =
            new OrderPlacedEvent("order-1", "customer-1", items, Instant.now());
        OrderConfirmedEvent confirmed =
            new OrderConfirmedEvent("order-1", Instant.now());

        fixture.given(placed, confirmed)
            .when(new ConfirmOrderCommand("order-1"))
            .expectException(IllegalStateException.class);
    }

    @Test
    void shouldNotAllowCancellationOfShippedOrder() {
        List<OrderItem> items = List.of(new OrderItem("SKU-001", 1, BigDecimal.TEN));
        Instant now = Instant.now();
        OrderPlacedEvent placed =
            new OrderPlacedEvent("order-1", "customer-1", items, now);
        OrderConfirmedEvent confirmed = new OrderConfirmedEvent("order-1", now);
        OrderShippedEvent shipped =
            new OrderShippedEvent("order-1", "TRACK-123", now);

        fixture.given(placed, confirmed, shipped)
            .when(new CancelOrderCommand("order-1", "Changed my mind"))
            .expectException(IllegalStateException.class);
    }

    @Test
    void shouldRejectOrderWithNoItems() {
        fixture.givenNoPriorActivity()
            .when(new PlaceOrderCommand("order-1", "customer-1", List.of()))
            .expectException(IllegalArgumentException.class);
    }
}

The given(events...) DSL replays prior events to build aggregate state before the command under test — exactly how Axon loads aggregates in production. This means your tests verify the entire event-sourcing lifecycle with zero infrastructure.


Running the Application

mvn spring-boot:run

Then exercise the API:

# Place an order
curl -X POST http://localhost:8080/api/orders \
  -H "Content-Type: application/json" \
  -d '{"customerId":"cust-1","items":[{"sku":"SKU-001","quantity":2,"unitPrice":49.99}]}'
# Response: "b4e3c1d2-..."

# Confirm it
curl -X PUT http://localhost:8080/api/orders/b4e3c1d2-.../confirm

# Ship it
curl -X PUT "http://localhost:8080/api/orders/b4e3c1d2-.../ship?trackingNumber=DHL-7890"

# Query it
curl http://localhost:8080/api/orders/b4e3c1d2-...

The H2 console is available at http://localhost:8080/h2-console — browse the DOMAIN_EVENT_ENTRY table to see every event the aggregate ever produced. That is your event store.


Common Pitfalls and Tips

1. No business logic in @EventSourcingHandler methods
These methods are called on every load from the event store, not just the first time. Any guard or validation there will fire on replay and can produce incorrect or inconsistent behaviour. Keep them pure: assign fields and nothing else.

2. Keep events immutable and schema-stable
Events are persisted forever. Once published, never change their structure — add new events instead, or use Axon's upcasting mechanism to transform old event formats at read time. Changing an event record and replaying will break any aggregate that consumed the old format.

3. Make projections idempotent
Event handlers can be replayed. A projection that double-counts a MoneyDepositedEvent or creates duplicate rows will produce wrong data after replay. Use upserts (save() on a JPA entity with a known ID) rather than blind inserts.

4. Use snapshots for aggregates with long event histories
Every command load replays all events from the beginning. For aggregates that accumulate hundreds of events over time, configure Axon's SnapshotTriggerDefinition to periodically write a snapshot of current state, so the replay starts from the most recent snapshot rather than event zero.

5. Use Axon Server in production
The embedded JPA event store stores events alongside your projection tables — convenient for development but not production-ready. Axon Server provides a dedicated, clusterable event store with built-in event replay, monitoring, and event-driven routing. It runs as a Docker container: docker run -d --name axon-server -p 8024:8024 -p 8124:8124 axoniq/axonserver.

6. Test projections separately
AggregateTestFixture tests the command side in isolation. Write a separate unit test for OrderProjection that fires events directly at the @EventHandler methods and asserts the read model, so you catch projection bugs without spinning up the full application context.


Conclusion

CQRS and Event Sourcing are powerful patterns that pay dividends when audit trails, temporal queries, or independent read/write scaling matter. Axon Framework 5 handles the infrastructure so you can focus on the domain — the aggregate, the commands, the events, and the projections are plain Java with minimal framework intrusion.

The order service we built demonstrates the full arc: command validation and event appending inside a @Aggregate, immutable state reconstruction through @EventSourcingHandler, a JPA-backed read model maintained by @EventHandler and served by @QueryHandler, and a clean REST API delegating to CommandGateway and QueryGateway. The AggregateTestFixture tests provide confidence that every state transition is correct before you write a single HTTP request.

From here, consider: adding sagas for multi-aggregate workflows (@SagaEventHandler), enabling Axon Server for production-grade event storage and replay, and exploring event upcasting to handle schema evolution gracefully as your domain grows.