Skip to content
javahacks.dev
Architecture

Clean Architecture in Java and Where It Gets Heavy

Clean architecture's four rings applied to a Java service, what it buys in testing and framework independence, and the point where the ceremony costs more.

7 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the Spring Boot and Swagger logos.

Clean Architecture promises a codebase where the business rules do not know about the web framework, the database or the message broker, so you can test them in milliseconds and change any of those without touching them. The promise is real. The cost, in a typical Spring Boot service, is also real: four layers of classes and mappers to move a name from a request to a row, and a team that spends a review explaining which package a class belongs in. Both are true, and the useful question is how much of the architecture a given service needs. This post draws the rings, builds a minimal version in Java with a runnable test, lists what you get and what it costs, shows lighter variants and compares it with layered and hexagonal structures. Examples use Java 25 and Spring Boot 4.

The rings

Robert C. Martin's clean architecture diagram is concentric circles with one rule: source code dependencies point inward only. Nothing in an inner ring may name anything in an outer ring.

RingContainsDepends on
EntitiesBusiness objects and rules that hold in any applicationNothing
Use casesOne class per application action, orchestrating entitiesEntities, and interfaces it declares itself
Interface adaptersControllers, presenters, repository implementations, mappersUse cases
Frameworks and driversSpring, the database, the web server, the brokerAdapters

The part that does the work is the interface the use case declares for the things it needs from the outside (a way to load an order, a way to send mail). The outer ring implements that interface, so the arrow of the source dependency points inward even though the runtime call flows outward. That reversal is the dependency inversion principle; the practical version is in dependency inversion beyond the slogan.

A minimal version in Java

Take one use case, placing an order, and build the rings from the inside. The entity carries a rule and no framework annotations:

src/main/java/dev/javahacks/shop/domain/Order.javajava
package dev.javahacks.shop.domain;

import java.util.UUID;

public final class Order {

    private final UUID id;
    private final long customerId;
    private final long totalCents;

    public Order(UUID id, long customerId, long totalCents) {
        if (totalCents <= 0) {
            throw new IllegalArgumentException("an order needs a positive total");
        }
        this.id = id;
        this.customerId = customerId;
        this.totalCents = totalCents;
    }

    public UUID id() { return id; }
    public long customerId() { return customerId; }
    public long totalCents() { return totalCents; }
}

The use case declares the ports it needs, in the vocabulary of the domain, and contains the application logic:

src/main/java/dev/javahacks/shop/usecase/PlaceOrder.javajava
package dev.javahacks.shop.usecase;

import dev.javahacks.shop.domain.Order;
import java.util.UUID;

public class PlaceOrder {

    public interface OrderStore {
        void save(Order order);
    }

    public interface Notifier {
        void orderPlaced(Order order);
    }

    public record Command(long customerId, long totalCents) { }

    private final OrderStore store;
    private final Notifier notifier;

    public PlaceOrder(OrderStore store, Notifier notifier) {
        this.store = store;
        this.notifier = notifier;
    }

    public UUID execute(Command command) {
        Order order = new Order(UUID.randomUUID(), command.customerId(), command.totalCents());
        store.save(order);
        notifier.orderPlaced(order);
        return order.id();
    }
}

The use case imports nothing from Spring or JPA. Its test needs no container, no database and no mocks library:

src/test/java/dev/javahacks/shop/usecase/PlaceOrderTest.javajava
class PlaceOrderTest {

    @Test
    void savesTheOrderAndNotifies() {
        var saved = new ArrayList<Order>();
        var notified = new ArrayList<Order>();
        var useCase = new PlaceOrder(saved::add, notified::add);

        UUID id = useCase.execute(new PlaceOrder.Command(7, 4999));

        assertThat(saved).hasSize(1);
        assertThat(saved.get(0).id()).isEqualTo(id);
        assertThat(notified).containsExactlyElementsOf(saved);
    }

    @Test
    void rejectsAZeroTotal() {
        var useCase = new PlaceOrder(o -> { }, o -> { });
        assertThatThrownBy(() -> useCase.execute(new PlaceOrder.Command(7, 0)))
                .isInstanceOf(IllegalArgumentException.class);
    }
}
Text
PlaceOrderTest > savesTheOrderAndNotifies() PASSED
PlaceOrderTest > rejectsAZeroTotal() PASSED

The two ports are single-method interfaces, so lambdas serve as the fakes. The outer rings then implement them with the real tools: a JPA adapter for OrderStore and a mail adapter for Notifier, each in an infrastructure package, plus a controller that turns HTTP into a Command:

src/main/java/dev/javahacks/shop/infra/JpaOrderStore.javajava
@Component
class JpaOrderStore implements PlaceOrder.OrderStore {

    private final OrderJpaRepository jpa;

    JpaOrderStore(OrderJpaRepository jpa) {
        this.jpa = jpa;
    }

    @Override
    public void save(Order order) {
        jpa.save(new OrderRow(order.id(), order.customerId(), order.totalCents()));
    }
}
src/main/java/dev/javahacks/shop/infra/Wiring.javajava
@Configuration
class Wiring {

    @Bean
    PlaceOrder placeOrder(PlaceOrder.OrderStore store, PlaceOrder.Notifier notifier) {
        return new PlaceOrder(store, notifier);
    }
}

OrderRow is a separate JPA entity, which is the cost the next sections count. The wiring class is the only place where the use case meets Spring.

What you get

Fast, honest tests of the rules. The test above runs in single-digit milliseconds because nothing starts. A suite of hundreds of use case tests that runs in a second changes how willing people are to refactor.

Replaceable infrastructure. Swapping the database, changing the broker or moving from REST to a message listener is a new adapter. In practice this is rarer than the diagram suggests, but the discipline pays off even without a swap, because you can see exactly where the framework ends.

A map of the code. A new person finds the behavior of the system in the use case classes, named after what the system does, rather than scattered through controllers and services. The names PlaceOrder, CancelOrder and RefundPayment are a table of contents.

Rules enforced by structure. With the dependency rule written down, an architecture test can fail the build if the domain package imports Spring. ArchUnit expresses that in a few lines, as in its user guide:

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

What it costs

The costs are mostly in volume and translation.

  • More classes per feature. A feature that was a controller, a service and a repository becomes a controller, a command, a use case, two ports, an adapter, an entity and a row class. Count them: the minimal example above has nine files for what a layered service writes in four.
  • Mapping everywhere. The domain Order and the JPA OrderRow hold the same data and need converting both ways. Each field added touches both classes and the mapper. Mapping libraries remove typing, not the coordination.
  • Anemic use cases. For a CRUD feature the use case just forwards to the port, and the ring structure adds ceremony with no rule to protect. Teams then invent rules to fill the classes, or give up the structure unevenly.
  • Lost framework features. Lazy loading, dirty checking and Spring Data's query derivation work on JPA entities. Hiding the entity behind a domain object means writing queries and change tracking yourself, or leaking JPA back in.
  • Onboarding. The vocabulary of rings and ports has to be taught, and a team that follows it halfway gets the cost without the benefit.

The weight is not evenly distributed. It is light for a service whose rules are rich and heavy for one that mostly moves data.

Make it lighter

Keep the part that gives most of the value and drop the rest.

  1. Keep the dependency rule, drop the extra rings. Domain and use cases in one inner package, adapters in another. Two rings are enough for most services.
  2. Annotate the domain. If the cost of a separate JPA row is a reason to give up, let the entity carry its JPA mappings and enforce only that the domain does not call out to controllers or clients. You trade purity for fewer classes, and many teams are right to.
  3. Skip use case classes for trivial reads. A query that returns a list can go from the controller to a read-only repository directly; keep use cases for operations that change state or enforce rules.
  4. Records for commands and results. They remove the boilerplate of the boundary objects.
  5. Package by feature first, then layer inside it. Rings inside orders/, customers/, catalog/, with package-private classes, as discussed in layered architecture in Spring and its real costs.
  6. Write the architecture test on day one. The rule only holds if a build checks it.

Compare

LayeredHexagonalClean
Core ideaEach layer calls the one belowThe domain defines ports; adapters plug inConcentric rings; dependencies point inward
Where the rules liveOften the service layerIn the application coreEntities and use cases
Database isThe bottom layerAn adapterAn outer detail
CostLowestMediumHighest
Good forCRUD and data-heavy servicesServices with several integrationsRule-rich domains with long lives

Hexagonal and clean architecture are close relatives: both invert the dependency on infrastructure, and clean adds an explicit use case ring and entity ring. A practical step-by-step version of the first is in hexagonal architecture with Spring Boot. Pick the lightest one that protects the rules you have.

Where this does not apply

For a CRUD service with a dozen tables and a handful of validations, clean architecture is a cost with no matching benefit; layers or even a controller over repositories is the right size. For a prototype, a script or a short-lived integration, the structure will not pay for itself before the code is deleted. And if the team is small and the domain is well understood, the cheapest way to get most of the value is the dependency rule, written down and tested, with nothing else added.

Taggedexplainer
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.