Skip to content

    System Design

    Hexagonal and Clean Architecture in Spring

    Structure a Spring service as ports and adapters: owned interfaces, a framework-free core, one composition root and ArchUnit rules that fail the build on leaks.

    By Published 15 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: Domain-Driven Design and Bounded Contexts

    What you'll learn: By the end of this lesson you will be able to lay out a Spring service as domain, application and adapters, tell driving ports from driven ports, keep Spring and SQL out of the core, name the one place that wires adapters, test the use case with no framework, write architecture rules that fail the build on a leak, and say honestly what the structure costs.

    An operating theatre has surgeons, and a supply room. The surgeon asks for "a scalpel", never for a brand, and the theatre works the same whether the supply room restocks from one vendor or another. The surgeon's requests are the application's own words; the porters who fetch things are the adapters. If a surgeon had to know which shelf, which vendor and which delivery van, every change of supplier would change the surgery. Hexagonal architecture is that arrangement for software: the business logic names what it needs, and small adapters at the edge deal with the shelves.

    Domain-driven design and bounded contexts and DDD tactical patterns shape the inside of the hexagon, and the ShopStream services stage introduces ports and adapters with a payment gateway. Client-server and n-tier separates layers from tiers. This lesson does not repeat those. It shows how the structure is laid out in a Spring service, what each package may import, where Spring is allowed to appear, and how to make a build fail when someone breaks the rule.

    Verified with Alistair Cockburn's hexagonal architecture article, Robert C. Martin's clean architecture article and the ArchUnit user guide (1.5.1 is the release on Maven Central at the time of writing), on 2026-12-01. The lab targets the Java 25 language level, runs on JDK 27 and uses Spring Boot 4.1.2.

    The core idea

    Source-code dependencies point inward, toward the business rules. The core defines the interfaces it needs (ports); outer code implements them (adapters); and one composition root, outside the core, chooses which adapter fills each port.

    Three illustrations run through it:

    • Minimal example: a PlaceOrder use case in plain Java, run with in-memory adapters and no Spring.
    • Realistic example: ShopStream's payment provider arriving late, in "In practice".
    • Failure example: a "domain" class holding a Spring JDBC type, caught by an architecture rule.

    Two sources state the idea in different words. Cockburn's intent is to "allow an application to equally be driven by users, programs, automated test or batch scripts" and to be "developed and tested in isolation from its eventual run-time devices and databases". Martin's Dependency Rule says that "source code dependencies can only point inwards". He lists the rings as entities, use cases, interface adapters, and frameworks and drivers, and says the architectures "all have the same objective, which is the separation of concerns". This lesson uses the hexagonal vocabulary (port, adapter) with the clean-architecture rule (inward only).

    A package layout that carries the rule

    The lab is a small ShopStream orders service. Its packages are the architecture:

    domain/                  Order, OrderLine, OrderStatus      imports nothing but the JDK
    application/             PlaceOrderService                  imports domain and its own ports
    application/port/in/     PlaceOrder (driving port)
    application/port/out/    OrderRepository, PaymentGateway (driven ports)
    adapter/web/             OrderController                    Spring MVC
    adapter/persistence/     JdbcOrderRepository, InMemoryOrderRepository
    adapter/payment/         FakePaymentGateway
    config/                  OrderConfig                        the composition root
    Package May import Must not import
    domain the JDK everything else, including Spring and SQL types
    application domain, its own ports, the JDK adapters, Spring, JDBC
    adapter.* application ports, domain, any framework other adapters
    config everything (nothing imports it)
    Driving adapters call input ports; driven adapters implement output ports; the core owns bothWeb adapter to Input port (calls); Input port to Core (implemented by); Core to Output ports (calls); SQL adapter to Output ports (implements); Payment adapter to Output ports (implements)Web adapter: controllerWeb adaptercontrollerInput port: PlaceOrderInput portPlaceOrderCore: use case, domainCoreuse case, domainOutput ports: repository, gatewayOutput portsrepository,gatewaySQL adapter: H2 in the labSQL adapterH2 in the labPayment adapter: provider clientPaymentadapterprovider clientcallsimplemented bycallsimplementsimplements

    Figure 1. The hexagon as a layout. How to read this: at run time the request flows left to right. At compile time the two adapters on the right point at the output ports, not the other way. The core never names an adapter, so swapping one touches nothing to its left.

    Two kinds of port

    Cockburn calls the sides "driving adapters and driven adapters", and says "the distinction between primary and secondary lies in who triggers or is in charge of the conversation". A driving (input) port is what the outside asks of the application. A driven (output) port is what the application asks of the outside. A port, in his words, "identifies a purposeful conversation"; an adapter "converts the API definition to the signals needed" by one external device.

    Both kinds are written in the application's words. The driving port:

    public interface PlaceOrder {
    
        OrderConfirmation place(PlaceOrderCommand command);
    }

    A driven port speaks about storage without a storage technology in it:

    public interface OrderRepository {
    
        /** A new order id that no other call has returned. */
        String nextId();
    
        /** Stores the order, replacing an earlier version with the same id. */
        void save(Order order);
    
        Optional<Order> findById(String id);
    }

    Two habits keep ports honest. Name a method for what the application wants (nextId, save), not for what SQL does (insertRow). And let the port say what can go wrong, so no adapter exception crosses it; the lab's PaymentGateway returns a boolean, which cannot say "provider unavailable", and the ShopStream services lesson shows a sealed result type for that.

    When you are unsure where a class belongs, ask three questions in order.

    flowchart TD accTitle: Which package does this class belong in accDescr: A class that holds a business rule with no framework type goes in the domain. A class that coordinates one use case through ports goes in the application. A class that names a framework, a database, a protocol or a vendor goes in an adapter. A class that chooses which adapter fills a port goes in the composition root. X["A new class"] --> Q1{"Does it name a framework, database, protocol or vendor?"} Q1 -->|"yes"| Q2{"Does it choose which adapter fills a port?"} Q2 -->|"yes"| R["Composition root (config)"] Q2 -->|"no"| A["An adapter"] Q1 -->|"no"| Q3{"Is it a business rule on its own data?"} Q3 -->|"yes"| D["Domain"] Q3 -->|"no"| U["Application: a use case or a port"]

    Figure 2. Placing a class. How to read this: the first question separates anything that touches the outside world. Everything that survives it is either a rule about its own data (domain) or coordination through ports (application).

    The use case and the domain are plain Java

    The use case has no annotation and no framework import. It is built by a test or by the composition root:

        @Override
        public OrderConfirmation place(PlaceOrderCommand command) {
            Order order = Order.place(
                    orders.nextId(),
                    command.lines().stream()
                            .map(l -> new OrderLine(l.sku(), l.quantity(), l.unitPriceCents()))
                            .toList());
            if (payments.authorize(order.id(), order.totalCents())) {
                order.confirm();
            } else {
                order.declinePayment();
            }
            orders.save(order);
            return new OrderConfirmation(order.id(), order.status(), order.totalCents());
        }

    The rules live in the domain: Order.place rejects an empty order, and confirm is allowed only from PLACED. That is the aggregate idea from the DDD lesson; here the point is that testing it needs only new:

        static PlaceOrderService inMemory() {
            return new PlaceOrderService(new InMemoryOrderRepository(), new FakePaymentGateway(LIMIT_CENTS));
        }

    No Spring context and no database: the same use case is later wired to H2 and to HTTP without a line of it changing.

    Three models, three translations

    The structure creates a cost you should name. The web adapter has its own request and response records (PlaceOrderRequest, OrderResponse); the domain has Order; the SQL adapter has rows. A change to the JSON does not touch the domain, and a change to the table does not touch the controller, but each boundary needs a mapping. The controller's mapping is the lab's:

            List<LineRequest> lines = request.lines() == null ? List.of() : request.lines();
            OrderConfirmation confirmation = placeOrder.place(new PlaceOrderCommand(lines.stream()
                    .map(l -> new PlaceOrderCommand.Line(l.sku(), l.quantity(), l.unitPriceCents()))
                    .toList()));
            int httpStatus = confirmation.status() == OrderStatus.CONFIRMED ? 201 : 422;

    Martin's article says the data crossing a boundary is typically "simple data structures" and warns against passing entities or database rows across it. Where an adapter rebuilds a domain object it uses a factory the domain provides, here Order.restore, so a stored order does not need a public setter. Skipping the mapping (one class used as JSON body, entity and domain object) is the usual shortcut and the usual source of leaks; the trade-off is stated below.

    Where Spring lives

    Spring is allowed in two places. Adapters use it freely: the controller is a @RestController, and the SQL adapter takes Spring's JdbcClient. The composition root uses it to wire:

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

    This is the one class that names JdbcOrderRepository and FakePaymentGateway together, and nothing imports it. Swapping the fake for a real provider adapter is a change in this file only.

    A real service needs a transaction boundary. The lab's JdbcOrderRepository.save issues several statements and the lab wraps them in no transaction, so a failure between them would leave a partial order; see Spring @Transactional for the mechanics. The design question is where the boundary goes. Around the use case is the natural place, because that is the unit of work, and it can be put there either by annotating the service (a framework annotation inside the application layer, a pragmatic exception you should make deliberately and write into your rules) or by a decorator in the composition root that leaves the use case plain. The lesson does not claim one is right; it asks you to choose on purpose.

    Enforcing the rule with a test

    A rule that lives in a diagram erodes. ArchUnit's user guide says it checks "the architecture of your Java code" by "analyzing given Java bytecode", imports classes with ClassFileImporter, offers package-dependency rules such as noClasses().that().resideInAPackage(...).should().dependOnClassesThat()..., and ships an onionArchitecture() check with domainModels, applicationServices and adapter packages. The lab writes its rules once, parameterised by a base package, so they can run against the real code and against a fixture:

            rules.put(
                    "the domain depends on nothing but itself and the JDK",
                    noClasses()
                            .that()
                            .resideInAPackage(base + ".domain..")
                            .should()
                            .dependOnClassesThat()
                            .resideOutsideOfPackages(base + ".domain..", "java.."));
            rules.put(
                    "the application depends only on the domain, itself and the JDK",
                    noClasses()
                            .that()
                            .resideInAPackage(base + ".application..")
                            .should()
                            .dependOnClassesThat()
                            .resideOutsideOfPackages(base + ".domain..", base + ".application..", "java.."));

    Three more rules say that no adapter depends on another adapter, that only the composition root names an adapter, and that the onion layout holds, with the config package explicitly exempt from the onion check because its job is to see everything. Without that exemption the onion rule flags OrderConfig, because it constructs adapters: the exemption is a statement of design, and a rule is only as good as its statement of what is exempt.

    A rule you have never seen fail is a rule you cannot trust, so the lab also includes a deliberately leaky fixture in the test sources, never wired into anything: a "domain" class holding a Spring JdbcClient, an "application" class that creates a concrete adapter, and a web adapter that reaches into the persistence adapter. Every rule must fail on it.

    sequenceDiagram accTitle: An architecture rule in the build accDescr: A developer pushes a change. The build compiles the classes and the architecture test imports the compiled bytecode. If a rule is violated the test fails with the class and line, the pull request cannot merge, and the developer moves the code behind a port. Otherwise the build continues to the other tests. participant Dev as Developer participant CI as Build participant Arch as Architecture test Dev->>CI: push a change CI->>CI: compile CI->>Arch: import compiled classes alt a rule is violated Arch-->>CI: fail, with class and line CI-->>Dev: cannot merge Dev->>Dev: move the code behind a port else all rules hold Arch-->>CI: pass CI->>CI: run the other tests end

    Figure 3. The rule as a gate. How to read this: the architecture test sits in the build like any other test. The cost of a leak becomes a red check on a pull request instead of a finding in a review next year.

    Adapters are tested against a contract

    A fake adapter is only useful if it behaves like the real one. The lab states the behaviour of an OrderRepository once, as four checks (ids never repeat, a round trip keeps lines in order, an unknown id is empty, saving again replaces rather than duplicates), and runs them against InMemoryOrderRepository and against JdbcOrderRepository on H2. The front-end version of this lesson, ports and adapters in the front end, calls the same idea a contract test and shows a fake that drifted. The two ideas are the same on both sides of the wire; the back end adds a database as the adapter that can disagree with the fake.

    Build it: one use case, driven and stored several ways

    This is the minimal example, a lab you can run. Run A drives the use case with no Spring and in-memory adapters. Run B swaps in the SQL adapter on H2, in memory, and runs the repository contract on both adapters. Run C puts the web adapter in a standalone MockMvc. Runs D and E run the architecture rules on the real code and on the leaky fixture.

    Goal. See one use case work unchanged behind three drivers and two stores, and see the architecture rules pass on the real code and fail on the fixture.

    Setup. From the repository's examples/spring-labs folder:

    cd examples/spring-labs && ./gradlew :labs:hexagonal-orders:test

    Tests assert each run and a golden test compares the report with examples/spring-labs/golden/hexagonal-orders.txt. The code is under examples/spring-labs/labs/hexagonal-orders/src/main/java/buildingai/labs/hexagonal/. The cart is illustrative: 2 x milk-1l at 129 cents and 1 x bread at 245 cents, and the fake payment gateway authorizes up to 10,000 cents.

    Expected output, captured from a real run (Spring Boot 4.1.2, ArchUnit 1.5.1, JDK 27, 2026-12-01):

    Run A. No Spring, no database: PlaceOrderService + InMemoryOrderRepository + FakePaymentGateway.
      place(cart)      -> OrderConfirmation[orderId=ord-1, status=CONFIRMED, totalCents=503]
      place(big cart)  -> OrderConfirmation[orderId=ord-2, status=PAYMENT_DECLINED, totalCents=13500]
      place(no lines)  -> IllegalArgumentException: an order needs at least one line
    
    Run B. The same use case with the SQL adapter (JdbcOrderRepository on H2, in memory).
      place(cart)      -> OrderConfirmation[orderId=ord-1, status=CONFIRMED, totalCents=503]
      stored order     -> CONFIRMED, [OrderLine[sku=milk-1l, quantity=2, unitPriceCents=129], OrderLine[sku=bread, quantity=1, unitPriceCents=245]]
      The contract, the same four checks run on both adapters:
        pass in memory, pass jdbc: nextId never repeats
        pass in memory, pass jdbc: save then findById returns the same lines in the same order
        pass in memory, pass jdbc: findById of an unknown id is empty
        pass in memory, pass jdbc: saving again replaces the order, it does not duplicate lines
    
    Run C. The web adapter alone: OrderController in a standalone MockMvc over the same use case (no server, no Spring context).
      POST /orders, the cart       -> 201 {"orderId":"ord-1","status":"CONFIRMED","totalCents":503}
      POST /orders, the big cart   -> 422 {"orderId":"ord-2","status":"PAYMENT_DECLINED","totalCents":13500}
      POST /orders, no lines       -> 400 {"error":"an order needs at least one line"}

    The same use case gives the same answer behind all three drivers. The declined order is still stored, as PAYMENT_DECLINED, and the controller translates that outcome into a 422 and the domain's rejection of an empty cart into a 400, so HTTP vocabulary stays in the adapter.

    Expected output, captured from a real run (the lab's runs D and E):

    Run D. Architecture rules (ArchUnit 1.5.1) on the compiled classes of buildingai.labs.hexagonal.
      classes imported: 20
      pass: the domain depends on nothing but itself and the JDK
      pass: the application depends only on the domain, itself and the JDK
      pass: no adapter depends on another adapter
      pass: only the composition root (config) names an adapter
      pass: the onion layout holds (domain, application, adapters; config is exempt)
    
    Run E. The same rules on a deliberately leaky fixture (buildingai.labs.leaky, in the test sources, never wired).
      FAIL (4 violations): the domain depends on nothing but itself and the JDK
      FAIL (3 violations): the application depends only on the domain, itself and the JDK
      FAIL (1 violation): no adapter depends on another adapter
      FAIL (3 violations): only the composition root (config) names an adapter
      FAIL (5 violations): the onion layout holds (domain, application, adapters; config is exempt)
      What the first failing rule reports:
        Constructor <buildingai.labs.leaky.domain.LeakyOrder.<init>(org.springframework.jdbc.core.simple.JdbcClient)> has parameter of type <org.springframework.jdbc.core.simple.JdbcClient> in (LeakyOrder.java:0)
        Field <buildingai.labs.leaky.domain.LeakyOrder.db> has type <org.springframework.jdbc.core.simple.JdbcClient> in (LeakyOrder.java:0)
        Method <buildingai.labs.leaky.domain.LeakyOrder.save()> calls method <org.springframework.jdbc.core.simple.JdbcClient$StatementSpec.update()> in (LeakyOrder.java:18)
        Method <buildingai.labs.leaky.domain.LeakyOrder.save()> calls method <org.springframework.jdbc.core.simple.JdbcClient.sql(java.lang.String)> in (LeakyOrder.java:18)
    Part What it shows
    Run A The core runs with new and in-memory adapters; the gateway's authorize decides confirmed or declined.
    Run B The SQL adapter and the in-memory adapter pass the same four checks, so the fake can be trusted for what those checks cover.
    Run C The web adapter owns status codes (201, 422, 400) and JSON; the core owns the outcomes.
    Run D Five rules pass on 20 compiled classes.
    Run E The same rules fail on the fixture, and the report names the class, the member and the line.

    Break it. Add import org.springframework.stereotype.Component; and a @Component annotation to PlaceOrderService: the application rule fails, naming the class. Remove both and re-run the tests.

    Stretch. Replace the boolean in PaymentGateway with a sealed result that has an Unavailable case, and make the use case decide what to do with it. Put a transaction around the use case through a decorator in OrderConfig.

    What the lab leaves out. A transaction boundary, a real payment provider, security, input validation beyond the domain's own checks, and event publication. The 20-class count and the 10,000-cent limit are lab facts, not recommendations.

    Trade-offs

    Structure Gains Costs Fits
    Layers by technology (controller, service, repository) Familiar, fast to write, few classes Entities and JSON shapes leak upward; tests need the framework Small CRUD services, short-lived code
    Hexagonal (ports and adapters) Core runs and tests without a framework; swappable edges A port, an adapter and a mapping per boundary; more files Services with real rules, several drivers or stores
    Hexagonal plus architecture tests The structure is enforced, not hoped for Rules to write and maintain; they encode a convention Teams and codebases that outlast their first authors

    The other side of this topic

    On the front end the same structure appears as owned interfaces, an HTTP adapter, a fake adapter and a composition root: see ports and adapters in the front end and layered and clean architecture for the UI. The difference is the adapter's enemy: in the browser it is a server whose shape changes, on the back end it is also a database whose behaviour a fake can quietly misstate.

    In practice: ShopStream's second payment provider

    This is the realistic example, an educational scenario on the course's running example, ShopStream; nothing in it describes a real company. Numbers other than the shared ShopStream figures are illustrative.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's orders service began as controller, service and repository over JPA entities. A second payment provider is now needed for one region. The authorization call is written inline in the order service, its failures are provider exceptions, and a unit test of the order rules needs the Spring context and a database, so the suite takes minutes (illustrative).

    Starting architecture

    Before: the order service calls the provider client directlyController to OrderService (calls); OrderService to Provider client (authorize); OrderService to JPA repository (save)Controller: uses entities as JSONControlleruses entities asJSONOrderService: rules + provider callsOrderServicerules + providercallsProvider client: raw exceptionsProviderclientraw exceptionsJPA repository: entitiesJPA repositoryentitiescallsauthorizesave

    Figure 4. The service that knows its provider. How to read this: the order rules and the provider client sit in one class, so a second provider means editing the rules, and the provider's exceptions travel straight up to the controller.

    Options considered

    Option Behaviour Problem
    A. Add an if (region) for the second provider Fast Rules and two vendors in one class; tests worse
    B. Hexagonal inside the service, one use case at a time Two payment adapters behind one port Mapping code and a period with both styles
    C. Split payments into its own service Independent deploys A network boundary before the seam is clean
    D. B plus architecture rules from day one Leaks cannot return unnoticed Rules to maintain

    The decision

    Option D. Introduce a PaymentGateway port in the application layer, move the existing provider code into an adapter, add the second as another adapter, and choose by region in the composition root. New use cases go through ports; old code stays behind a legacy adapter until moved. The architecture rules cover the new packages first. The port returns a result that can say "unavailable", so no provider exception crosses it.

    Rollout and verification

    The team ports one use case, PlaceOrder, then adds the repository contract run against the real adapter and its fake, and a contract for the gateway fake. Verification: the use-case tests run without Spring, the adapter contract passes for both providers' adapters, and the architecture test fails on a deliberate import added in a throwaway branch.

    The 2 a.m. failure

    The page reads: checkouts return 500 for the second region. The provider is slow, and its adapter, written in a hurry, lets the client's timeout exception escape through the port. The use case does not expect it, so the order is neither confirmed nor declined and the error reaches the controller.

    The checks: the stack trace's top frames (adapter, not use case), the provider's latency, and whether the port's result type has a case for "unavailable". The mitigation is catching the exception in the adapter and returning that case so the use case can decide (retry later, or mark the order pending). The lasting fix is a contract test for the gateway that includes a timing-out fake, and a rule that adapters throw only the port's own exceptions.

    Architect's notes

    • The dependency rule is the point. Ports, adapters and packages are how you keep it true.
    • Ports are written in the application's words, and they say what can go wrong.
    • Wire in one place. If two classes choose adapters, you have two composition roots.
    • Write the exemption down. Name what the rules allow (here the config package) rather than letting each rule discover it.
    • Test the rules as you test code. Show each rule failing once.
    • Pay for the structure where it earns something: real rules, several drivers, a fake that speeds tests.

    Common mistakes

    • One class as JSON, entity and domain object. Every boundary change now changes all three.
    • An adapter exception crossing the port. The use case then handles vendor errors it should never see.
    • Ports named for the technology. insertRow is an adapter's word, not the application's.
    • A fake that is never checked against the real adapter. It drifts and the tests lie.
    • Annotating the domain. One @Entity or @Component in the core and the rule is already broken.
    • Rules nobody has seen fail. They may be checking an empty set of classes.

    Key takeaways

    • Dependencies point inward; the core owns the interfaces and outer code implements them.
    • Driving ports are what the world asks of the core; driven ports are what the core asks of the world.
    • Spring belongs in adapters and the composition root, not in the domain or use cases.
    • Mapping at each boundary is the price of keeping the models independent.
    • Architecture rules turn a convention into a build failure.
    • A contract run against every adapter keeps fakes honest.

    Practice exercises

    Exercise 1 (20 min). For a ShopStream shipping-label feature, list its driving ports, its driven ports and the adapter you would write for each.

    Exercise 2 (45 min). Run the lab. Add @Component to PlaceOrderService, run the tests, say which rule fails and why, then restore the file.

    Exercise 3 (1 hour). Change PaymentGateway.authorize to return a sealed result with Approved, Declined and Unavailable. Update the use case, the fake and the contract.

    Exercise 4 (2 hours). Decide where the transaction boundary goes for PlaceOrder and implement it two ways: an annotation on the service, and a decorator in OrderConfig. Write the architecture rule each choice needs.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments