A typical Spring Boot service, after a few months of incremental additions, tends to look like this: @Service classes injecting Spring Data JPA @Repository interfaces directly, JPA entities leaking all the way into the REST controller, and business logic scattered across all three layers depending on who touched the code last. Testing a single business rule in isolation becomes impossible without spinning up a full Spring context or an in-memory H2 database. Hexagonal architecture addresses exactly this problem: it isolates business logic from everything framework-related, so the domain can be tested and evolved independently from Spring, JPA, or the exposure protocol.

The principle: ports and adapters

The core idea, introduced by Alistair Cockburn, is to place the business domain at the center with no outward dependency. The domain defines interfaces, called "ports": inbound ports (the use cases the application exposes) and outbound ports (what the domain needs to function, like persistence or a call to an external service). Adapters implement those ports: an inbound adapter translates an HTTP request or a queue message into a use case call, an outbound adapter translates a domain need (persist an order) into a concrete technical call (JPA, a REST call, and so on).

The dependency rule is strict: the domain depends on nothing, the application layer depends on the domain, infrastructure depends on both, never the reverse. Spring makes this inversion trivial through dependency injection: you inject the port interface, and Spring resolves the concrete implementation at startup.

Concrete package layout

com.example.orders
├── domain
│   ├── Order.java
│   ├── OrderStatus.java
│   └── OrderPolicy.java
├── application
│   ├── port.in
│   │   └── CancelOrderUseCase.java
│   ├── port.out
│   │   └── OrderRepository.java
│   └── CancelOrderService.java
└── infrastructure
    ├── adapter.in.web
    │   └── OrderController.java
    └── adapter.out.persistence
        ├── OrderJpaEntity.java
        ├── OrderJpaRepository.java
        └── OrderRepositoryAdapter.java

The domain package contains no Spring or JPA annotations at all. It's plain Java, carrying the business rules.

public class Order {
    private final OrderId id;
    private OrderStatus status;
    private final List<OrderLine> lines;

    public void cancel() {
        if (status == OrderStatus.SHIPPED) {
            throw new OrderAlreadyShippedException(id);
        }
        this.status = OrderStatus.CANCELLED;
    }
}

The outbound port is an interface defined in the application layer, expressed in business vocabulary, not persistence vocabulary:

public interface OrderRepository {
    Optional<Order> findById(OrderId id);
    void save(Order order);
}

The use case orchestrates the domain through that port, with no idea whether persistence is JPA, MongoDB, or a plain file:

@Service
public class CancelOrderService implements CancelOrderUseCase {

    private final OrderRepository orderRepository;

    public CancelOrderService(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    @Override
    @Transactional
    public void cancel(OrderId orderId) {
        Order order = orderRepository.findById(orderId)
            .orElseThrow(() -> new OrderNotFoundException(orderId));
        order.cancel();
        orderRepository.save(order);
    }
}

The outbound adapter lives in infrastructure and carries the entire dependency on Spring Data JPA, including the mapping between the JPA entity and the domain object:

@Component
public class OrderRepositoryAdapter implements OrderRepository {

    private final OrderJpaRepository jpaRepository;
    private final OrderMapper mapper;

    public OrderRepositoryAdapter(OrderJpaRepository jpaRepository, OrderMapper mapper) {
        this.jpaRepository = jpaRepository;
        this.mapper = mapper;
    }

    @Override
    public Optional<Order> findById(OrderId id) {
        return jpaRepository.findById(id.value()).map(mapper::toDomain);
    }

    @Override
    public void save(Order order) {
        jpaRepository.save(mapper.toEntity(order));
    }
}

The web-side inbound adapter translates the HTTP request into a use case call, never touching the JPA entity:

@RestController
@RequestMapping("/orders")
public class OrderController {

    private final CancelOrderUseCase cancelOrderUseCase;

    public OrderController(CancelOrderUseCase cancelOrderUseCase) {
        this.cancelOrderUseCase = cancelOrderUseCase;
    }

    @PostMapping("/{id}/cancel")
    public ResponseEntity<Void> cancel(@PathVariable String id) {
        cancelOrderUseCase.cancel(new OrderId(id));
        return ResponseEntity.noContent().build();
    }
}

Why this separation actually pays off

The most tangible benefit is test speed and reliability. Order.cancel() can be tested with a plain JUnit test, no Spring, no database, in a few milliseconds:

@Test
void cancel_shouldThrow_whenOrderAlreadyShipped() {
    Order order = Order.shipped(OrderId.of("ORD-1"));

    assertThrows(OrderAlreadyShippedException.class, order::cancel);
}

Adapters get tested with the tools suited to their layer: @DataJpaTest for the persistence adapter against an embedded database, @WebMvcTest for the controller with the use case mocked out. That avoids heavy integration tests (a full @SpringBootTest) just to verify a business rule that has nothing to do with Spring.

The second benefit is the ability to swap infrastructure without touching business logic. Replacing Spring Data JPA with a call to an external service, or adding a second inbound adapter (a Kafka consumer alongside the REST controller) for the same use case, requires no change to the domain or the use case, only a new adapter implementing the existing port.

Adding a second inbound adapter without touching business logic

The real test of a properly built hexagonal architecture is adding a new delivery mechanism without modifying the domain or the use case. Say order cancellation now also needs to be triggerable from a Kafka message emitted by a warehouse system, alongside the existing REST controller. With the CancelOrderUseCase inbound port already in place, all that's needed is a new adapter:

@Component
public class OrderCancellationKafkaListener {

    private final CancelOrderUseCase cancelOrderUseCase;

    public OrderCancellationKafkaListener(CancelOrderUseCase cancelOrderUseCase) {
        this.cancelOrderUseCase = cancelOrderUseCase;
    }

    @KafkaListener(topics = "warehouse.order-cancellations", groupId = "orders-service")
    public void onMessage(OrderCancellationEvent event) {
        try {
            cancelOrderUseCase.cancel(new OrderId(event.orderId()));
        } catch (OrderNotFoundException | OrderAlreadyShippedException ex) {
            log.warn("Could not apply cancellation from warehouse event {}: {}", event.orderId(), ex.getMessage());
        }
    }
}

Neither CancelOrderService, nor Order, nor the OrderRepository interface changed. This is exactly what dependency inversion buys: the business rule ("an already-shipped order can't be cancelled") lives in exactly one place, and applies identically whether it's triggered by an HTTP request or an asynchronous message. Without this separation, the temptation would have been to duplicate the status == SHIPPED check inside the Kafka listener, with a real risk of it drifting out of sync with the REST controller's version as both evolve.

Reducing the cost of domain-to-persistence mapping

The most common complaint against this architecture, the volume of mapping code between the JPA entity and the domain object, can be reduced without giving up the separation. A tool like MapStruct generates the mapper at compile time from a plain annotated interface, avoiding hand-written field assignments:

@Mapper(componentModel = "spring")
public interface OrderMapper {
    Order toDomain(OrderJpaEntity entity);
    OrderJpaEntity toEntity(Order order);
}

This doesn't remove the mapping layer, but shrinks its maintenance cost down to defining the interface: edge cases (a nested relation that doesn't map trivially, a computed field) get handled with explicit @Mapping methods, while the bulk of the mapping stays auto-generated and verified at compile time rather than at runtime.

The tradeoff worth being honest about

This structure has a real cost: more classes, more mapping between domain objects and JPA entities, more interfaces to maintain. On a simple CRUD feature with no meaningful business logic, this discipline is pure overhead: a @Service calling a Spring Data @Repository directly does the exact same job with a tenth of the code. Hexagonal architecture pays for itself when business logic is rich enough and changes often enough that isolating it is worth more than it costs, or when several delivery mechanisms (REST, messaging, CLI) need to share the same use cases.

When structure alone isn't enough

Splitting into ports and adapters solves a dependency problem, not an anemic model problem. If Order stays a plain bag of getters and setters and all the logic for cancel() migrates into CancelOrderService, the problem has just moved, not disappeared: the domain becomes a disguised data layer again, and business rules end up diluted across application services just like before, only inside a package with a different name. Hexagonal architecture gives you the right dependency structure; it's the discipline of putting behavior inside the domain objects themselves (in the spirit of DDD) that delivers the actual benefit.

Takeaway

Hexagonal architecture in Spring Boot means making infrastructure depend on the domain through interfaces, never the reverse, which Spring's dependency injection makes natural to implement. The concrete payoff shows up in test speed and ease of swapping infrastructure; the cost is extra classes and mapping that only pays off when the business complexity actually warrants it.