Video in progress
How do you organize hexagonal architecture (ports and adapters) at the package level in a Spring Boot project?
In the center are the domain and use cases, free of framework dependencies, with their ports (interfaces) right there. Outside are the adapters: REST controller, JPA repository, Kafka listener. Dependencies only point inward.
📖 Answer
A sample structure for one bounded context:
com.shop.ordering
├─ domain // Order, Money, rules: no Spring/JPA annotations
├─ application // use cases: PlaceOrder, CancelOrder
│ ├─ port.in // PlaceOrderUseCase (incoming port)
│ └─ port.out // OrderRepository, PaymentGateway (outgoing port)
└─ adapter
├─ in.web // @RestController -> port.in
├─ in.messaging // @KafkaListener -> port.in
├─ out.persistence // JPA entity + Spring Data, implements port.out
└─ out.payment // HTTP client, implements port.out
The main rule: domain and application never import adapter. Spring wiring happens in @Configuration classes.
The cost:
- Mapping. If the JPA entity and the domain model are separate, you need a mapper at every boundary. In a small service this can take 30% of the code. A pragmatic option: put JPA annotations on the domain class and accept that "impurity".
- Incoming port interfaces are often unnecessary: the rule isn't broken if the controller calls the use case class directly.
- The benefit: domain tests run in milliseconds and don't need a Spring context; when the DB or broker is replaced, only the adapter changes.
When it pays off: complex business rules, a long-lived system, several input channels. Putting hexagonal on a plain CRUD service means many files and little value. It's good when the team takes one project as the example and the others follow that template.
Sign up to mark studied questions and save your progress.