package com.example.order.core; import com.example.order.domain.Order; import com.example.order.ports.inbound.CreateOrderUseCase; import com.example.order.ports.outbound.OrderRepositoryPort; import java.math.BigDecimal; import java.util.UUID; public class OrderService implements CreateOrderUseCase private final OrderRepositoryPort orderRepositoryPort; public OrderService(OrderRepositoryPort orderRepositoryPort) this.orderRepositoryPort = orderRepositoryPort; @Override public Order createOrder(String product, BigDecimal price) Order order = new Order(UUID.randomUUID(), product, price); // Execute domain logic order.completePayment(); // Persist via outbound port orderRepositoryPort.save(order); return order; Use code with caution. Step 4: The Primary Adapter (REST Controller)
Implement the inbound port within the domain layer. This class orchestrates the business logic and calls outbound ports.
Designing Hexagonal Architecture with Java, published by Packt
Now we implement the external layers, such as an in-memory database adapter.
: Learn to build a "Domain Hexagon" using entities and value objects that are entirely technology-agnostic.
The core philosophy is simple:
If your team decides to migrate from SQL to a NoSQL database, you only rewrite the Secondary Adapter layer. The core application logic remains untouched, un-retested, and completely safe.
+-----------------------------------------+ | OUTSIDE | | [ REST Controller / UI ] | | | | +-----------------------+ | | | INSIDE | | | | [ Business Logic ] | | | ===> | | ===> | | (In) | +-----------+ | (Out) | | Port | | Domain | | Port | | | | Models | | | | +-----+-----------+-----+ | | | | [ Database / Spring ] | | OUTSIDE | +-----------------------------------------+
package ports.inbound; import domain.Order; import java.util.UUID; public interface CreateOrderUseCase UUID createOrder(String product, double price); Use code with caution.
com.example.orders ├── domain/ <-- Pure Java (No frameworks) │ ├── model/ │ │ └── Order.java │ └── exception/ │ └── OrderNotFoundException.java ├── ports/ <-- Interfaces │ ├── inbound/ │ │ └── CreateOrderUseCase.java │ └── outbound/ │ └── OrderRepositoryPort.java └── infrastructure/ <-- Frameworks & Technologies ├── adapters/ │ ├── inbound/ │ │ └── OrderRestController.java │ └── outbound/ │ └── PostgresOrderRepositoryAdapter.java └── config/ └── BeanConfiguration.java Use code with caution. 2. The Domain Layer
This comprehensive guide breaks down the principles of Hexagonal Architecture (Ports and Adapters) in Java, providing practical code examples and structural insights that mirror high-quality engineering literature. 1. What is Hexagonal Architecture?
