Skip to content
javahacks.dev
Architecture

Hexagonal Architecture in Java With Spring Boot Example

Structure a Spring Boot application with ports and adapters so the domain has no framework imports, with an order example, package layout and tests.

7 min read
Summarize in AI
Flat illustration of a start button surrounded by Spring Boot starters, with the Spring Boot, Apache Maven and Gradle logos.

Hexagonal architecture, also called ports and adapters, is dependency inversion applied to a whole application. The goal is modest and useful: keep the business rules free of technology, so they can be tested in isolation and survive a change of web framework or database. This post builds a small order service with Spring Boot 4 on Java 25 and shows the package layout, the ports, two adapters, the wiring and the tests. It also states the cost plainly, because a design that adds types has to earn them. The principle underneath is explained in dependency inversion beyond the slogan.

The picture

Text
REST controller --> [ inbound port ]  ==>  DOMAIN  ==>  [ outbound port ] <-- JPA adapter
Kafka listener  -->                                                       <-- HTTP client adapter
   (driving adapters)                                                         (driven adapters)

The domain sits in the middle. Adapters on the left call into it through inbound ports, which are use cases. Adapters on the right are called by it through outbound ports, which are interfaces the domain declares for what it needs. Nothing in the domain knows which adapters exist, and that single rule is the whole architecture.

Package layout

Text
dev.javahacks.shop
  domain/
    Order.java
    OrderLine.java
  application/
    PlaceOrderUseCase.java
    OrderRepository.java
    PaymentGateway.java
    PlaceOrderService.java
  adapter/
    in/web/OrderController.java
    out/persistence/JpaOrderRepository.java
    out/payment/StripePaymentGateway.java
  config/
    BeanConfig.java

domain holds entities and value objects. application holds the ports and the services that implement the use cases. adapter holds everything that touches the outside world, split by direction. The rule that makes the layout meaningful is about imports: domain and application import nothing from adapter and nothing from Spring. Some teams tolerate @Service in the application package. Stricter ones wire beans in config, which keeps the core a plain Java library.

The domain and the ports

java
// domain
public final class Order {

    private final OrderId id;
    private final List<OrderLine> lines = new ArrayList<>();

    public void addLine(Sku sku, int quantity, Money unitPrice) {
        if (quantity <= 0) {
            throw new IllegalArgumentException("quantity must be positive");
        }
        lines.add(new OrderLine(sku, quantity, unitPrice));
    }

    public Money total() {
        return lines.stream().map(OrderLine::subtotal).reduce(Money.ZERO, Money::plus);
    }
}

// application: inbound port
public interface PlaceOrderUseCase {
    OrderId place(PlaceOrderCommand command);
}

// application: outbound ports
public interface OrderRepository {
    void save(Order order);
}

public interface PaymentGateway {
    Receipt charge(Money amount, CustomerId customer);
}

The rule about positive quantities lives in the entity, where every caller meets it, not in a controller where only one does. The ports are described in the domain's language: the repository saves an Order, the gateway charges an amount. Neither mentions SQL or HTTP.

The use case ties them together:

java
public class PlaceOrderService implements PlaceOrderUseCase {

    private final OrderRepository orders;
    private final PaymentGateway payments;

    public PlaceOrderService(OrderRepository orders, PaymentGateway payments) {
        this.orders = orders;
        this.payments = payments;
    }

    @Override
    public OrderId place(PlaceOrderCommand command) {
        Order order = Order.create(command.customer());
        command.lines().forEach(l -> order.addLine(l.sku(), l.quantity(), l.unitPrice()));
        payments.charge(order.total(), command.customer());
        orders.save(order);
        return order.id();
    }
}

The adapters

A driving adapter turns a protocol into a command and calls the port:

java
@RestController
class OrderController {

    private final PlaceOrderUseCase placeOrder;

    OrderController(PlaceOrderUseCase placeOrder) {
        this.placeOrder = placeOrder;
    }

    @PostMapping("/orders")
    ResponseEntity<Void> place(@RequestBody PlaceOrderRequest request) {
        OrderId id = placeOrder.place(request.toCommand());
        return ResponseEntity.created(URI.create("/orders/" + id.value())).build();
    }
}

A driven adapter implements an outbound port and maps between the domain object and whatever the technology needs:

java
@Component
class JpaOrderRepository implements OrderRepository {

    private final SpringDataOrderRepository jpa;

    JpaOrderRepository(SpringDataOrderRepository jpa) {
        this.jpa = jpa;
    }

    @Override
    public void save(Order order) {
        jpa.save(OrderEntity.from(order));
    }
}

The JPA entity is a separate class from the domain Order. That costs a mapping, and it buys a domain with no annotations, no proxies and no lazy loading to reason about. The entity side is covered in the Hibernate guide.

Wiring

java
@Configuration
class BeanConfig {

    @Bean
    PlaceOrderUseCase placeOrder(OrderRepository orders, PaymentGateway payments) {
        return new PlaceOrderService(orders, payments);
    }
}

The configuration class is the only place that sees both sides, and it is allowed to, because wiring is its job. Spring supplies the adapters as beans and the core receives them through its constructor.

Tests

java
class PlaceOrderServiceTest {

    @Test
    void chargesAndSaves() {
        var orders = new InMemoryOrderRepository();
        var payments = new FakePaymentGateway();

        new PlaceOrderService(orders, payments).place(sampleCommand());

        assertEquals(1, orders.count());
        assertEquals(Money.of(2_490), payments.lastCharge());
    }
}

There is no Spring context and no database, so this runs in milliseconds and a hundred like it cost less than one @SpringBootTest. Each adapter gets its own integration test against the real technology, as laid out in a practical testing strategy. An ArchUnit test that fails when domain imports adapter keeps the rule honest after the people who wrote it have moved on.

Where transactions and validation go

Two questions come up on the first real project. Transactions belong around the use case, because a use case is one unit of work: a payment and a save succeed together or not at all. Put the transaction annotation on the service in the application package, or wrap the service with a transactional decorator in the configuration class if you want the core to stay free of Spring. Either way the adapters do not open transactions; the repository adapter joins the one that is already open.

Validation splits into two kinds. Shape validation, such as "the email field is present and well formed", belongs in the driving adapter, where the request is parsed, and it can use Bean Validation. Business validation, such as "quantity must be positive" or "this customer may not exceed their limit", belongs in the domain, because it is a rule of the business and must hold for every entry point. Putting it in the controller means a Kafka listener bypasses it.

Errors cross the boundary as domain exceptions

The domain should signal failure in its own terms: an OutOfStock or a PaymentDeclined, not an HTTP status and not a SQL exception. The driving adapter translates those into the protocol's vocabulary, so the web adapter maps PaymentDeclined to a 402 and the messaging adapter sends a rejection event. The driven adapters do the opposite, catching technology exceptions such as a timeout from the payment API and rethrowing something the domain understands. This translation is the part that keeps technology details from leaking inward.

Growing the design gradually

Do not start with every port. Begin with one use case, one inbound and one outbound port, and the rule that the domain imports nothing from outside. Add ports as pressure appears: a second way to trigger a use case, a second storage, a slow dependency you want to fake. Teams that draw the whole hexagon on day one tend to ship interfaces that have a single implementation and no reason to exist, and they pay the mapping cost for years.

The cost

You pay in types and mapping. A request becomes a command, the command becomes domain objects, and the domain object becomes an entity, with a conversion at each step. For simple create-read-update-delete screens these layers carry no logic, and the mapping code is pure ceremony. The structure pays off when the domain has real rules, several entry points such as HTTP and messaging, or integrations that change. Compare it with layered architecture and clean architecture.

Keep the hexagon honest with a test

The design survives only while the domain stays free of framework imports, and that is easy to lose in a rushed week. Make the rule a test that fails the build:

java
@AnalyzeClasses(packages = "dev.javahacks.shop", importOptions = ImportOption.DoNotIncludeTests.class)
class HexagonTest {

    @ArchTest
    static final ArchRule domainIsFrameworkFree =
        noClasses().that().resideInAPackage("..domain..")
            .should().dependOnClassesThat().resideInAnyPackage(
                "org.springframework..", "jakarta.persistence..", "com.fasterxml.jackson..");

    @ArchTest
    static final ArchRule adaptersDependOnDomainNotOnEachOther =
        noClasses().that().resideInAPackage("..adapter.web..")
            .should().dependOnClassesThat().resideInAPackage("..adapter.persistence..");
}

The first rule is the one that matters: the day an @Entity or a Spring annotation appears in the domain package, the test names the class. The second keeps the web adapter from reaching around the ports into the database code, which is the shortcut that turns a hexagon back into layers. Both run in milliseconds with the unit tests, so the rule costs nothing to keep, and it turns the diagram in the architecture document into something that is checked on every build. If a rule has to be broken, the exception is written in the test with a comment, where the next reviewer sees it.

When a simpler design wins

A small service that mostly stores and returns records fits a plain layered design better, and splitting it into ports adds more files than behavior. Start simple and extract ports when a second adapter or a testing pain appears. The pattern comes from Alistair Cockburn, and the original article on hexagonal architecture and the Spring Boot reference are the primary sources.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.