What you will build#
A small order service with two use cases — place an order (and charge for it) and get an order — structured as Ports and Adapters:
- The domain model enforces business rules in plain Java.
- The application service orchestrates use cases and talks to the outside world only through ports.
- Adapters connect the core to HTTP (Spring MVC), a database (Spring Data JPA with H2) and a payment provider (simulated, so the example needs no credentials).
- Tests cover each part at the right level. The use-case tests run without Spring and without a database.
The full source is in examples/spring-hexagonal-orders/. It targets Java 21 and Spring Boot 4.1.1.
cd examples/spring-hexagonal-orders
mvn verify # compiles and runs all 17 tests
mvn spring-boot:run # starts the service on http://localhost:8080
Package structure#
com.example.orders
├── domain/ ← business rules; depends on nothing but the JDK
│ ├── Order.java (aggregate root)
│ ├── OrderLine.java, Money.java, OrderId.java, CustomerId.java (value objects)
│ ├── OrderStatus.java
│ └── InvalidOrderException.java
├── application/
│ ├── port/in/ ← inbound ports: what the app can do
│ │ ├── PlaceOrderUseCase.java
│ │ └── GetOrderQuery.java
│ ├── port/out/ ← outbound ports: what the app needs
│ │ ├── OrderRepository.java
│ │ └── PaymentPort.java
│ └── service/
│ └── OrderApplicationService.java (implements the inbound ports)
├── adapter/
│ ├── in/web/ ← driving adapter: HTTP → inbound ports
│ │ ├── OrderController.java, PlaceOrderRequest.java, OrderResponse.java
│ │ └── ApiExceptionHandler.java
│ └── out/
│ ├── persistence/ ← driven adapter: OrderRepository with JPA
│ │ ├── JpaOrderRepositoryAdapter.java, OrderJpaEntity.java
│ │ └── SpringDataOrderRepository.java
│ └── payment/ ← driven adapter: PaymentPort
│ └── SimulatedPaymentAdapter.java
├── config/
│ └── UseCaseConfiguration.java (composition root for the core)
└── OrdersApplication.java
flowchart LR
web["adapter.in.web"] --> portin["application.port.in"]
service["application.service"] -. implements .-> portin
service --> portout["application.port.out"]
service --> domain["domain"]
portin --> domain
portout --> domain
persistence["adapter.out.persistence"] -. implements .-> portout
payment["adapter.out.payment"] -. implements .-> portout
persistence --> domain
payment --> domain
web --> domain
config["config"] --> service
config --> portoutNothing in domain or application imports Spring, JPA or Jackson. Only the adapters and config know about the framework.
The domain model#
Order is an aggregate root (see DDD Fundamentals). Every state change goes through a method that protects the invariants:
package com.example.orders.domain;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
/**
* Aggregate root. All changes go through methods that protect the invariants:
* - an order has between 1 and MAX_LINES lines, all in one currency;
* - the status only moves along allowed transitions;
* - the total is always derived from the lines, never stored separately.
* No framework annotations: persistence mapping lives in an adapter.
*/
public final class Order {
public static final int MAX_LINES = 50;
private final OrderId id;
private final CustomerId customerId;
private final List<OrderLine> lines;
private final Instant placedAt;
private OrderStatus status;
private String paymentReference;
private Order(OrderId id, CustomerId customerId, List<OrderLine> lines, Instant placedAt,
OrderStatus status, String paymentReference) {
this.id = Objects.requireNonNull(id);
this.customerId = Objects.requireNonNull(customerId);
this.lines = List.copyOf(lines);
this.placedAt = Objects.requireNonNull(placedAt);
this.status = Objects.requireNonNull(status);
this.paymentReference = paymentReference;
checkLines(this.lines);
}
/** Factory for new orders: the only way to start the lifecycle. */
public static Order place(OrderId id, CustomerId customerId, List<OrderLine> lines, Instant now) {
return new Order(id, customerId, lines, now, OrderStatus.PENDING_PAYMENT, null);
}
/** Recreates an order from storage. Used only by persistence adapters. */
public static Order rehydrate(OrderId id, CustomerId customerId, List<OrderLine> lines, Instant placedAt,
OrderStatus status, String paymentReference) {
return new Order(id, customerId, lines, placedAt, status, paymentReference);
}
public void markPaid(String paymentReference) {
requireStatus(OrderStatus.PENDING_PAYMENT, "mark as paid");
this.paymentReference = Objects.requireNonNull(paymentReference);
this.status = OrderStatus.PAID;
}
public void markPaymentDeclined() {
requireStatus(OrderStatus.PENDING_PAYMENT, "decline payment for");
this.status = OrderStatus.PAYMENT_DECLINED;
}
public void cancel() {
requireStatus(OrderStatus.PENDING_PAYMENT, "cancel");
this.status = OrderStatus.CANCELLED;
}
public Money total() {
Money sum = Money.zero(lines.getFirst().unitPrice().currency());
for (OrderLine line : lines) {
sum = sum.plus(line.total());
}
return sum;
}
private void requireStatus(OrderStatus expected, String action) {
if (status != expected) {
throw new InvalidOrderException("Cannot " + action + " order " + id + " in status " + status);
}
}
private static void checkLines(List<OrderLine> lines) {
if (lines.isEmpty()) {
throw new InvalidOrderException("An order needs at least one line");
}
if (lines.size() > MAX_LINES) {
throw new InvalidOrderException("An order can have at most " + MAX_LINES + " lines");
}
var currency = lines.getFirst().unitPrice().currency();
if (lines.stream().anyMatch(l -> !l.unitPrice().currency().equals(currency))) {
throw new InvalidOrderException("All lines must use the same currency");
}
}
public OrderId id() { return id; }
public CustomerId customerId() { return customerId; }
public List<OrderLine> lines() { return lines; }
public Instant placedAt() { return placedAt; }
public OrderStatus status() { return status; }
public String paymentReference() { return paymentReference; }
}Money is a value object: immutable, compared by value, and it refuses to add amounts in different currencies.
package com.example.orders.domain;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Currency;
import java.util.Objects;
/** Value object: an amount in one currency. Immutable, compared by value. */
public record Money(BigDecimal amount, Currency currency) {
public Money {
Objects.requireNonNull(amount, "amount");
Objects.requireNonNull(currency, "currency");
if (amount.signum() < 0) {
throw new InvalidOrderException("Money cannot be negative: " + amount);
}
amount = amount.setScale(currency.getDefaultFractionDigits(), RoundingMode.HALF_EVEN);
}
public static Money of(String amount, String currencyCode) {
return new Money(new BigDecimal(amount), Currency.getInstance(currencyCode));
}
public static Money zero(Currency currency) {
return new Money(BigDecimal.ZERO, currency);
}
public Money plus(Money other) {
requireSameCurrency(other);
return new Money(amount.add(other.amount), currency);
}
public Money times(int factor) {
return new Money(amount.multiply(BigDecimal.valueOf(factor)), currency);
}
public boolean isGreaterThan(Money other) {
requireSameCurrency(other);
return amount.compareTo(other.amount) > 0;
}
private void requireSameCurrency(Money other) {
if (!currency.equals(other.currency)) {
throw new InvalidOrderException("Currency mismatch: " + currency + " vs " + other.currency);
}
}
@Override
public String toString() {
return amount.toPlainString() + " " + currency.getCurrencyCode();
}
}stateDiagram-v2
[*] --> PENDING_PAYMENT : Order.place(...)
PENDING_PAYMENT --> PAID : markPaid(reference)
PENDING_PAYMENT --> PAYMENT_DECLINED : markPaymentDeclined()
PENDING_PAYMENT --> CANCELLED : cancel()
PAID --> [*]
PAYMENT_DECLINED --> [*]
CANCELLED --> [*]Ports#
Inbound ports#
package com.example.orders.application.port.in;
import com.example.orders.domain.Order;
import java.math.BigDecimal;
import java.util.List;
/**
* Inbound port: what the outside world can ask the application to do.
* Expressed in application terms — no HTTP, no JSON, no Spring types.
*/
public interface PlaceOrderUseCase {
Order placeOrder(PlaceOrderCommand command);
record PlaceOrderCommand(String customerId, String currency, List<Line> lines) {
public PlaceOrderCommand {
lines = List.copyOf(lines);
}
public record Line(String productId, int quantity, BigDecimal unitPrice) {
}
}
}package com.example.orders.application.port.in;
import com.example.orders.domain.Order;
import com.example.orders.domain.OrderId;
/** Inbound port for reads. Kept separate so callers depend only on what they use. */
public interface GetOrderQuery {
/** @throws OrderNotFoundException if no order has this id */
Order getOrder(OrderId id);
class OrderNotFoundException extends RuntimeException {
public OrderNotFoundException(OrderId id) {
super("Order " + id + " not found");
}
}
}The command is a record with plain types. It belongs to the application, not to HTTP — a message listener or a batch job could create it just as easily.
Outbound ports#
package com.example.orders.application.port.out;
import com.example.orders.domain.Order;
import com.example.orders.domain.OrderId;
import java.util.Optional;
/**
* Outbound port: the application needs to store and load orders.
* It does not care whether that is JPA, JDBC, a document store or memory.
*/
public interface OrderRepository {
void save(Order order);
Optional<Order> findById(OrderId id);
}package com.example.orders.application.port.out;
import com.example.orders.domain.Money;
import com.example.orders.domain.OrderId;
/**
* Outbound port: charge a customer for an order. The order id doubles as an
* idempotency key, so a retried call must not charge twice.
*/
public interface PaymentPort {
PaymentOutcome charge(OrderId orderId, Money amount);
sealed interface PaymentOutcome {
record Approved(String reference) implements PaymentOutcome { }
record Declined(String reason) implements PaymentOutcome { }
}
}PaymentPort documents an important contract: the order ID is an idempotency key. If the call is retried after a timeout, the provider must not charge twice.
The application service#
package com.example.orders.application.service;
import com.example.orders.application.port.in.GetOrderQuery;
import com.example.orders.application.port.in.PlaceOrderUseCase;
import com.example.orders.application.port.out.OrderRepository;
import com.example.orders.application.port.out.PaymentPort;
import com.example.orders.application.port.out.PaymentPort.PaymentOutcome;
import com.example.orders.domain.CustomerId;
import com.example.orders.domain.Money;
import com.example.orders.domain.Order;
import com.example.orders.domain.OrderId;
import com.example.orders.domain.OrderLine;
import java.time.Clock;
import java.util.Currency;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
/**
* Application service: orchestrates a use case. It translates the command
* into domain objects, lets the aggregate enforce business rules, and talks
* to the outside world only through outbound ports. Plain Java — Spring
* wiring happens in the config package.
*/
public final class OrderApplicationService implements PlaceOrderUseCase, GetOrderQuery {
private final OrderRepository orders;
private final PaymentPort payments;
private final Clock clock;
private final Supplier<OrderId> ids;
public OrderApplicationService(OrderRepository orders, PaymentPort payments, Clock clock, Supplier<OrderId> ids) {
this.orders = Objects.requireNonNull(orders);
this.payments = Objects.requireNonNull(payments);
this.clock = Objects.requireNonNull(clock);
this.ids = Objects.requireNonNull(ids);
}
@Override
public Order placeOrder(PlaceOrderCommand command) {
Currency currency = Currency.getInstance(command.currency());
List<OrderLine> lines = command.lines().stream()
.map(l -> new OrderLine(l.productId(), l.quantity(), new Money(l.unitPrice(), currency)))
.toList();
Order order = Order.place(ids.get(), new CustomerId(command.customerId()), lines, clock.instant());
orders.save(order); // 1. record the intent first
switch (payments.charge(order.id(), order.total())) { // 2. call the outside world
case PaymentOutcome.Approved approved -> order.markPaid(approved.reference());
case PaymentOutcome.Declined declined -> order.markPaymentDeclined();
}
orders.save(order); // 3. record the outcome
return order;
}
@Override
public Order getOrder(OrderId id) {
return orders.findById(id).orElseThrow(() -> new OrderNotFoundException(id));
}
}The order is saved before the payment call and again afterwards. If the process crashes during the payment call, a PENDING_PAYMENT order remains as evidence, and a reconciliation job can query the provider with the order ID. This is deliberate: the use case is not wrapped in one database transaction, because holding a transaction open across a remote call ties up a database connection for as long as the provider takes to respond.
Inbound adapter: the REST controller#
package com.example.orders.adapter.in.web;
import com.example.orders.application.port.in.GetOrderQuery;
import com.example.orders.application.port.in.PlaceOrderUseCase;
import com.example.orders.domain.Order;
import com.example.orders.domain.OrderId;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
/**
* Inbound (driving) adapter: translates HTTP into calls on inbound ports and
* domain results back into HTTP. It contains no business rules.
*/
@RestController
@RequestMapping("/orders")
class OrderController {
private final PlaceOrderUseCase placeOrder;
private final GetOrderQuery getOrder;
OrderController(PlaceOrderUseCase placeOrder, GetOrderQuery getOrder) {
this.placeOrder = placeOrder;
this.getOrder = getOrder;
}
@PostMapping
ResponseEntity<OrderResponse> place(@Valid @RequestBody PlaceOrderRequest request) {
Order order = placeOrder.placeOrder(request.toCommand());
var location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(order.id()).toUri();
return ResponseEntity.created(location).body(OrderResponse.from(order));
}
@GetMapping("/{id}")
OrderResponse get(@PathVariable String id) {
return OrderResponse.from(getOrder.getOrder(OrderId.of(id)));
}
}The request DTO validates the shape of the input with Jakarta Validation; business rules stay in the domain:
package com.example.orders.adapter.in.web;
import com.example.orders.application.port.in.PlaceOrderUseCase.PlaceOrderCommand;
import jakarta.validation.Valid;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import java.math.BigDecimal;
import java.util.List;
/**
* HTTP request body. Validation here is about the *shape* of the input
* (required fields, formats). Business rules stay in the domain.
*/
public record PlaceOrderRequest(
@NotBlank String customerId,
@NotBlank @Pattern(regexp = "[A-Z]{3}", message = "must be an ISO 4217 code") String currency,
@NotEmpty List<@Valid Line> lines) {
public record Line(
@NotBlank String productId,
@Min(1) int quantity,
@NotNull @DecimalMin("0.00") BigDecimal unitPrice) {
}
PlaceOrderCommand toCommand() {
return new PlaceOrderCommand(customerId, currency, lines.stream()
.map(l -> new PlaceOrderCommand.Line(l.productId(), l.quantity(), l.unitPrice()))
.toList());
}
}Exceptions are translated into RFC 9457 Problem Details. HTTP status codes are web knowledge, so the mapping lives in the adapter:
package com.example.orders.adapter.in.web;
import com.example.orders.application.port.in.GetOrderQuery.OrderNotFoundException;
import com.example.orders.domain.InvalidOrderException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* Maps application and domain exceptions to RFC 9457 Problem Details.
* The mapping is HTTP knowledge, so it belongs in the web adapter.
*/
@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail notFound(OrderNotFoundException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
}
@ExceptionHandler(InvalidOrderException.class)
ProblemDetail businessRuleViolated(InvalidOrderException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_CONTENT, e.getMessage());
}
@ExceptionHandler(IllegalArgumentException.class)
ProblemDetail badInput(IllegalArgumentException e) {
// e.g. an unknown currency code or a malformed order id
return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, e.getMessage());
}
}| Situation | Raised by | HTTP status |
|---|---|---|
| Malformed JSON or failed bean validation | Spring MVC | 400 Bad Request |
| Unknown currency code, malformed ID | JDK (IllegalArgumentException) | 400 Bad Request |
| Business rule violated (for example, mixed currencies) | Domain (InvalidOrderException) | 422 Unprocessable Content |
| Order not found | Application (OrderNotFoundException) | 404 Not Found |
Outbound adapters#
Persistence#
The JPA entity is a separate class, owned by the adapter. JPA’s requirements — a no-argument constructor, mutable fields, annotations — never reach the domain model.
package com.example.orders.adapter.out.persistence;
import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Embeddable;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OrderColumn;
import jakarta.persistence.Table;
import jakarta.persistence.Version;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Persistence model, shaped for the database and owned by this adapter.
* Keeping it separate from the domain Order means JPA's requirements
* (no-arg constructor, mutable fields, annotations) never leak into the core.
*/
@Entity
@Table(name = "orders")
class OrderJpaEntity {
@Id
UUID id;
@Column(nullable = false)
String customerId;
@Column(nullable = false, length = 3)
String currency;
@Column(nullable = false, length = 32)
String status;
String paymentReference;
@Column(nullable = false)
Instant placedAt;
@Version
Long version;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "order_lines", joinColumns = @JoinColumn(name = "order_id"))
@OrderColumn(name = "line_no")
List<LineEmbeddable> lines = new ArrayList<>();
protected OrderJpaEntity() {
// required by JPA
}
@Embeddable
static class LineEmbeddable {
@Column(nullable = false)
String productId;
int quantity;
@Column(nullable = false, precision = 19, scale = 4)
BigDecimal unitPrice;
protected LineEmbeddable() {
}
LineEmbeddable(String productId, int quantity, BigDecimal unitPrice) {
this.productId = productId;
this.quantity = quantity;
this.unitPrice = unitPrice;
}
}
}package com.example.orders.adapter.out.persistence;
import com.example.orders.application.port.out.OrderRepository;
import com.example.orders.domain.CustomerId;
import com.example.orders.domain.Money;
import com.example.orders.domain.Order;
import com.example.orders.domain.OrderId;
import com.example.orders.domain.OrderLine;
import com.example.orders.domain.OrderStatus;
import org.springframework.stereotype.Component;
import java.util.Currency;
import java.util.Optional;
/**
* Outbound (driven) adapter: implements the OrderRepository port with JPA
* and maps between the domain model and the persistence model.
*/
@Component
class JpaOrderRepositoryAdapter implements OrderRepository {
private final SpringDataOrderRepository jpa;
JpaOrderRepositoryAdapter(SpringDataOrderRepository jpa) {
this.jpa = jpa;
}
@Override
public void save(Order order) {
OrderJpaEntity entity = jpa.findById(order.id().value()).orElseGet(OrderJpaEntity::new);
entity.id = order.id().value();
entity.customerId = order.customerId().value();
entity.currency = order.total().currency().getCurrencyCode();
entity.status = order.status().name();
entity.paymentReference = order.paymentReference();
entity.placedAt = order.placedAt();
entity.lines.clear();
order.lines().forEach(l -> entity.lines.add(
new OrderJpaEntity.LineEmbeddable(l.productId(), l.quantity(), l.unitPrice().amount())));
jpa.save(entity);
}
@Override
public Optional<Order> findById(OrderId id) {
return jpa.findById(id.value()).map(JpaOrderRepositoryAdapter::toDomain);
}
private static Order toDomain(OrderJpaEntity e) {
Currency currency = Currency.getInstance(e.currency);
return Order.rehydrate(
new OrderId(e.id),
new CustomerId(e.customerId),
e.lines.stream()
.map(l -> new OrderLine(l.productId, l.quantity, new Money(l.unitPrice, currency)))
.toList(),
e.placedAt,
OrderStatus.valueOf(e.status),
e.paymentReference);
}
}The @Version field gives optimistic locking: if two requests modify the same order concurrently, the second save fails instead of silently overwriting the first.
Payment#
package com.example.orders.adapter.out.payment;
import com.example.orders.application.port.out.PaymentPort;
import com.example.orders.domain.Money;
import com.example.orders.domain.OrderId;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Outbound adapter standing in for a payment provider's HTTP API, so the
* example runs without credentials. It approves charges up to a configured
* limit and is idempotent per order id, as a real provider integration must be.
* A production adapter would use RestClient, timeouts and retries here —
* and the application core would not change.
*/
@Component
class SimulatedPaymentAdapter implements PaymentPort {
private final BigDecimal approvalLimit;
private final Map<OrderId, PaymentOutcome> processed = new ConcurrentHashMap<>();
SimulatedPaymentAdapter(@Value("${payments.simulated.approval-limit:1000.00}") BigDecimal approvalLimit) {
this.approvalLimit = approvalLimit;
}
@Override
public PaymentOutcome charge(OrderId orderId, Money amount) {
return processed.computeIfAbsent(orderId, id -> amount.amount().compareTo(approvalLimit) <= 0
? new PaymentOutcome.Approved("PAY-" + id.value().toString().substring(0, 8))
: new PaymentOutcome.Declined("amount exceeds limit"));
}
}A production adapter would call the provider over HTTP with Spring’s RestClient, set connection and read timeouts, retry only idempotent failures, and map the provider’s responses — exactly as the Adapter pattern article describes. The application core would not change.
Wiring#
The core classes carry no Spring annotations, so one configuration class turns them into beans:
package com.example.orders.config;
import com.example.orders.application.port.out.OrderRepository;
import com.example.orders.application.port.out.PaymentPort;
import com.example.orders.application.service.OrderApplicationService;
import com.example.orders.domain.OrderId;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.Clock;
/**
* Composition root for the application core. The core has no Spring
* annotations; this class is the only place that turns it into beans.
*/
@Configuration(proxyBeanMethods = false)
class UseCaseConfiguration {
@Bean
Clock clock() {
return Clock.systemUTC();
}
@Bean
OrderApplicationService orderApplicationService(OrderRepository orders, PaymentPort payments, Clock clock) {
return new OrderApplicationService(orders, payments, clock, OrderId::newId);
}
}Spring injects the single OrderApplicationService bean wherever a PlaceOrderUseCase or a GetOrderQuery is required, because the class implements both interfaces.
Request flow#
sequenceDiagram
autonumber
participant Client as HTTP client
participant C as OrderController
participant S as OrderApplicationService
participant O as Order (aggregate)
participant R as JpaOrderRepositoryAdapter
participant P as SimulatedPaymentAdapter
Client->>C: POST /orders {customerId, currency, lines}
C->>C: validate request, map to PlaceOrderCommand
C->>S: placeOrder(command)
S->>O: Order.place(id, customer, lines, now)
O-->>S: order (PENDING_PAYMENT)
S->>R: save(order)
S->>P: charge(orderId, total)
P-->>S: Approved("PAY-…")
S->>O: markPaid("PAY-…")
S->>R: save(order)
S-->>C: order (PAID)
C-->>Client: 201 Created, Location: /orders/{id}Testing strategy#
Each kind of test checks one thing and starts only what it needs.
| Test | What runs | What it proves | Relative cost |
|---|---|---|---|
OrderTest | Domain classes only | Invariants and state transitions | Lowest: plain JUnit |
OrderApplicationServiceTest | Application service with hand-written fakes | Use-case orchestration: payment outcomes, save order | Lowest: plain JUnit |
OrderControllerTest (@WebMvcTest) | Spring MVC slice, ports mocked | JSON mapping, validation, status codes | Medium: web slice context |
JpaOrderRepositoryAdapterTest (@DataJpaTest) | JPA with embedded H2 | Domain ↔ table mapping in both directions | Medium: JPA slice context |
OrdersApplicationTests (@SpringBootTest) | Everything | The pieces are wired correctly end to end | Highest: full context |
Testing a use case without Spring or a database#
package com.example.orders.application.service;
import com.example.orders.application.port.in.GetOrderQuery.OrderNotFoundException;
import com.example.orders.application.port.in.PlaceOrderUseCase.PlaceOrderCommand;
import com.example.orders.application.port.out.OrderRepository;
import com.example.orders.application.port.out.PaymentPort;
import com.example.orders.application.port.out.PaymentPort.PaymentOutcome;
import com.example.orders.domain.Money;
import com.example.orders.domain.Order;
import com.example.orders.domain.OrderId;
import com.example.orders.domain.OrderStatus;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Use-case tests without Spring or a database: the outbound ports are
* replaced by small hand-written fakes. This is the main payoff of the
* hexagonal structure.
*/
class OrderApplicationServiceTest {
private static final OrderId FIXED_ID = new OrderId(UUID.fromString("00000000-0000-0000-0000-000000000001"));
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-03-01T12:00:00Z"), ZoneOffset.UTC);
/** Fake outbound adapter: a map instead of a database. */
static final class InMemoryOrderRepository implements OrderRepository {
final Map<OrderId, Order> store = new HashMap<>();
int saves;
@Override
public void save(Order order) {
saves++;
store.put(order.id(), order);
}
@Override
public Optional<Order> findById(OrderId id) {
return Optional.ofNullable(store.get(id));
}
}
private final InMemoryOrderRepository repository = new InMemoryOrderRepository();
private final List<Money> charges = new ArrayList<>();
private OrderApplicationService serviceWithPayments(PaymentOutcome outcome) {
PaymentPort payments = (orderId, amount) -> {
charges.add(amount);
return outcome;
};
return new OrderApplicationService(repository, payments, CLOCK, () -> FIXED_ID);
}
private static PlaceOrderCommand command() {
return new PlaceOrderCommand("c-42", "EUR", List.of(
new PlaceOrderCommand.Line("book", 2, new BigDecimal("12.50")),
new PlaceOrderCommand.Line("pen", 1, new BigDecimal("3.00"))));
}
@Test
void approvedPaymentMarksTheOrderPaid() {
var service = serviceWithPayments(new PaymentOutcome.Approved("PAY-123"));
Order order = service.placeOrder(command());
assertThat(order.status()).isEqualTo(OrderStatus.PAID);
assertThat(order.paymentReference()).isEqualTo("PAY-123");
assertThat(order.placedAt()).isEqualTo(Instant.parse("2026-03-01T12:00:00Z"));
assertThat(charges).containsExactly(Money.of("28.00", "EUR"));
assertThat(repository.findById(FIXED_ID)).contains(order);
}
@Test
void declinedPaymentIsRecordedNotThrown() {
var service = serviceWithPayments(new PaymentOutcome.Declined("insufficient funds"));
Order order = service.placeOrder(command());
assertThat(order.status()).isEqualTo(OrderStatus.PAYMENT_DECLINED);
assertThat(repository.store.get(FIXED_ID).status()).isEqualTo(OrderStatus.PAYMENT_DECLINED);
}
@Test
void theOrderIsStoredBeforeThePaymentIsAttempted() {
var service = new OrderApplicationService(repository, (orderId, amount) -> {
assertThat(repository.findById(orderId)).isPresent(); // intent recorded first
return new PaymentOutcome.Approved("PAY-1");
}, CLOCK, () -> FIXED_ID);
service.placeOrder(command());
assertThat(repository.saves).isEqualTo(2);
}
@Test
void unknownOrderIsReported() {
var service = serviceWithPayments(new PaymentOutcome.Approved("unused"));
assertThatThrownBy(() -> service.getOrder(FIXED_ID)).isInstanceOf(OrderNotFoundException.class);
}
}The payment port is a lambda, and the repository is a small class backed by a HashMap. The tests need no mocking framework, no application context and no database, and the clock and IDs are fixed so that every assertion is exact. This is the main practical payoff of the hexagonal structure.
Adapter tests#
The web adapter is tested with a Spring MVC slice and mocked inbound ports:
package com.example.orders.adapter.in.web;
import com.example.orders.application.port.in.GetOrderQuery;
import com.example.orders.application.port.in.PlaceOrderUseCase;
import com.example.orders.domain.CustomerId;
import com.example.orders.domain.InvalidOrderException;
import com.example.orders.domain.Money;
import com.example.orders.domain.Order;
import com.example.orders.domain.OrderId;
import com.example.orders.domain.OrderLine;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import java.time.Instant;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Adapter test: only the web layer is started. The inbound ports are mocked,
* so this verifies HTTP mapping, validation and error translation — nothing else.
*/
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired
MockMvc mvc;
@MockitoBean
PlaceOrderUseCase placeOrder;
@MockitoBean
GetOrderQuery getOrder;
private static final String VALID_BODY = """
{"customerId":"c-42","currency":"EUR",
"lines":[{"productId":"book","quantity":2,"unitPrice":12.50}]}
""";
@Test
void placesAnOrderAndReturns201WithLocation() throws Exception {
Order order = Order.place(OrderId.of("00000000-0000-0000-0000-000000000007"), new CustomerId("c-42"),
List.of(new OrderLine("book", 2, Money.of("12.50", "EUR"))), Instant.parse("2026-03-01T12:00:00Z"));
given(placeOrder.placeOrder(any())).willReturn(order);
mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content(VALID_BODY))
.andExpect(status().isCreated())
.andExpect(header().string("Location", "http://localhost/orders/00000000-0000-0000-0000-000000000007"))
.andExpect(jsonPath("$.status").value("PENDING_PAYMENT"))
.andExpect(jsonPath("$.total").value(25.00));
}
@Test
void rejectsMalformedInputWith400() throws Exception {
mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON)
.content("""
{"customerId":"","currency":"euro","lines":[]}
"""))
.andExpect(status().isBadRequest());
}
@Test
void translatesBusinessRuleViolationsTo422() throws Exception {
given(placeOrder.placeOrder(any())).willThrow(new InvalidOrderException("All lines must use the same currency"));
mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content(VALID_BODY))
.andExpect(status().isUnprocessableContent())
.andExpect(jsonPath("$.detail").value("All lines must use the same currency"));
}
@Test
void unknownOrderIs404() throws Exception {
OrderId id = OrderId.of("00000000-0000-0000-0000-000000000009");
given(getOrder.getOrder(id)).willThrow(new GetOrderQuery.OrderNotFoundException(id));
mvc.perform(get("/orders/{id}", id.toString()))
.andExpect(status().isNotFound());
}
}The persistence adapter is tested against a real JPA provider and an embedded database:
package com.example.orders.adapter.out.persistence;
import com.example.orders.domain.CustomerId;
import com.example.orders.domain.Money;
import com.example.orders.domain.Order;
import com.example.orders.domain.OrderId;
import com.example.orders.domain.OrderLine;
import com.example.orders.domain.OrderStatus;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import org.springframework.context.annotation.Import;
import java.time.Instant;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Adapter integration test: real JPA and an embedded database, no web layer
* and no application service. Verifies the mapping in both directions.
*/
@DataJpaTest
@Import(JpaOrderRepositoryAdapter.class)
class JpaOrderRepositoryAdapterTest {
@Autowired
JpaOrderRepositoryAdapter adapter;
@Test
void savesAndLoadsAnOrderWithItsLines() {
Order order = Order.place(OrderId.newId(), new CustomerId("c-42"), List.of(
new OrderLine("book", 2, Money.of("12.50", "EUR")),
new OrderLine("pen", 1, Money.of("3.00", "EUR"))), Instant.parse("2026-03-01T12:00:00Z"));
order.markPaid("PAY-9");
adapter.save(order);
Order loaded = adapter.findById(order.id()).orElseThrow();
assertThat(loaded.status()).isEqualTo(OrderStatus.PAID);
assertThat(loaded.paymentReference()).isEqualTo("PAY-9");
assertThat(loaded.lines()).containsExactlyElementsOf(order.lines());
assertThat(loaded.total()).isEqualTo(Money.of("28.00", "EUR"));
}
@Test
void updatesAnExistingOrder() {
Order order = Order.place(OrderId.newId(), new CustomerId("c-1"),
List.of(new OrderLine("book", 1, Money.of("9.99", "EUR"))), Instant.parse("2026-03-01T12:00:00Z"));
adapter.save(order);
order.markPaymentDeclined();
adapter.save(order);
assertThat(adapter.findById(order.id()).orElseThrow().status()).isEqualTo(OrderStatus.PAYMENT_DECLINED);
}
}Common implementation mistakes#
@Transactionalon the use case around a remote call. See the trade-off above.- Mapping in the wrong place. JSON mapping belongs in the web adapter and table mapping in the persistence adapter. The application service should not know about either.
- Testing the core through
@SpringBootTestonly. Slow tests discourage testing, and failures are hard to locate. Test the core directly. - Leaking Spring types into ports.
Page<Order>orResponseEntityin a port signature couples the core to Spring. - Ports for everything. This example has four ports, each with a stated reason. It has no interface for the application service implementation or for value objects.
Interview questions and answers#
How do you structure a Spring Boot application with Hexagonal Architecture?
Split it into domain, application (with port.in, port.out and service), adapter.in and adapter.out, plus a configuration package. Domain and application code are framework-free. Adapters use Spring. A @Configuration class creates the application services as beans.
How do you test a use case without starting Spring?
Construct the application service directly, passing in-memory fakes or lambdas for the outbound ports and a fixed Clock. Assert on the returned domain object and on what the fakes recorded.
Why keep a separate JPA entity? To keep persistence concerns — annotations, no-argument constructors, mutable fields, lazy loading — out of the domain model, and to let the schema and the model evolve independently. The cost is mapping code.
Where do transactions go in a hexagonal application?
Usually at the application-service boundary — either with @Transactional on a Spring-managed bean, or explicitly through a transaction port. Avoid holding a transaction open across remote calls.
Which status code would you return when a business rule fails? 422 Unprocessable Content for a syntactically valid request that violates a business rule; 400 for malformed input; 409 Conflict for concurrency conflicts such as an optimistic-locking failure.
Summary#
- The domain and application packages are plain Java and own every port.
- Adapters translate HTTP, JPA and provider APIs to and from the core’s language.
- One configuration class wires the core into Spring.
- Tests are layered: fast core tests, focused adapter slice tests and one end-to-end test.
- Each port exists for a stated reason; avoid interfaces without one.
Related topics#
- Layered versus Hexagonal Architecture
- Domain-Driven Design Fundamentals
- Dependency Injection in Java
- Designing an Order Management System
References#
- Alistair Cockburn. “Hexagonal Architecture”, 2005.
- Spring Boot reference documentation — testing slices and auto-configuration.
- Spring Boot 4.0 Migration Guide — modular starters and test annotations.
- RFC 9457: Problem Details for HTTP APIs.
- Tom Hombergs. Get Your Hands Dirty on Clean Architecture, 2nd edition. Packt, 2023.