Video in progress

What does hexagonal architecture (ports and adapters) look like in a Spring Boot project in practice, and when is it overkill?

The domain and use cases are in the center, and they know only their own interfaces (ports); Spring, JPA, Kafka and HTTP are outer adapters. It pays off in a complex domain and a long-lived system; in a simple CRUD service it just doubles the number of files.

📖 Answer

Take the Adapter pattern from the class level up to the architecture level and you get hexagonal. The package structure looks roughly like this:

order/
  domain/        Order, OrderLine, Money — no Spring, no JPA
  application/   PlaceOrderUseCase, port/out/OrderRepository, port/out/PaymentPort
  adapter/
    in/web/      OrderController
    out/persistence/  OrderJpaEntity, OrderJpaRepository, OrderPersistenceAdapter
    out/payment/      AcmePaymentAdapter

The rule is that dependencies point only inward. domain imports nothing, and application imports only domain. You have to enforce this with an ArchUnit test, not with words; otherwise in three months someone adds @Entity to the domain.

What you get: you test domain rules without Spring, in milliseconds; swapping the database or the broker is limited to an adapter; and when you read the code, business logic is separated from infrastructure.

The cost: the domain model and the JPA entity are separate, with mapping between them. Every new field changes in three places. You partly give up JPA conveniences like lazy loading and dirty checking.

I often use the pragmatic variant: I leave the JPA annotations on the domain class itself (they're just metadata), but I keep ports/adapters strictly for external integrations (payment, SMS, other services). Most of the benefit comes from exactly that boundary.