Structuring Clean Architecture in Spring Boot 3
There was a time when OrderService.java in my project hit 1,200 lines. Inside was a tangled mess: calculating discounts, validating inventory, directly calling EntityManager, and even firing off emails via RestTemplate. Every time we touched the promotional logic, the team worried about breaking the checkout flow.
The traditional 3-tier architecture (Controller – Service – Repository) works great for prototyping. However, as business logic grows, the Service layer quickly turns into a dumping ground. Clean Architecture solves this at the root: isolating core business logic and pushing frameworks and databases to the outer edges.
Here is the actual folder structure of the Order module our team is running in production:
com.itfromzero.order
├── domain # Pure POJO, strictly no Spring imports
│ ├── model # Entity, Value Object, Business Rules
│ │ └── Order.java
│ └── port # Communication contracts (Interfaces)
│ ├── in # Inbound use cases
│ │ └── CreateOrderUseCase.java
│ └── out # Outbound ports: DB, payment gateway, Message Queue
│ └── OrderRepositoryPort.java
├── application # Orchestrates business workflows
│ └── service
│ └── OrderService.java
└── infrastructure # Dependency layer: Spring, JPA, Redis, Kafka
├── adapter
│ ├── in
│ │ └── web # REST Controller, Request/Response DTO
│ │ └── OrderController.java
│ └── out
│ └── persistence # Spring Data JPA Repository, JPA Entity
│ ├── OrderJpaEntity.java
│ ├── SpringDataOrderRepository.java
│ └── OrderPersistenceAdapter.java
└── config # Spring Bean instantiation
└── OrderBeanConfig.java
To see the difference clearly, let’s examine the three core components:
1. Pure Java Domain Model
No Lombok, no Hibernate annotations. All order state validation logic is encapsulated right here:
package com.itfromzero.order.domain.model;
import java.math.BigDecimal;
import java.util.UUID;
public class Order {
private final UUID id;
private final String customerId;
private final BigDecimal totalAmount;
private OrderStatus status;
public Order(UUID id, String customerId, BigDecimal totalAmount) {
if (totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException("Order total amount must be greater than 0");
}
this.id = id;
this.customerId = customerId;
this.totalAmount = totalAmount;
this.status = OrderStatus.CREATED;
}
public void complete() {
if (this.status != OrderStatus.CREATED) {
throw new IllegalStateException("Only orders in CREATED status can be completed");
}
this.status = OrderStatus.COMPLETED;
}
public UUID getId() { return id; }
public String getCustomerId() { return customerId; }
public BigDecimal getTotalAmount() { return totalAmount; }
public OrderStatus getStatus() { return status; }
}
2. Inbound & Outbound Ports
Ports are simply Java interfaces that act as communication gateways:
// Inbound Port: Represents a Use Case
package com.itfromzero.order.domain.port.in;
import com.itfromzero.order.domain.model.Order;
import java.math.BigDecimal;
public interface CreateOrderUseCase {
Order execute(String customerId, BigDecimal amount);
}
// Outbound Port: Data persistence contract
package com.itfromzero.order.domain.port.out;
import com.itfromzero.order.domain.model.Order;
public interface OrderRepositoryPort {
Order save(Order order);
}
3. Application Service (Pure Java)
OrderService focuses strictly on business logic. It has no idea whether the data is persisted into PostgreSQL or MongoDB:
package com.itfromzero.order.application.service;
import com.itfromzero.order.domain.model.Order;
import com.itfromzero.order.domain.port.in.CreateOrderUseCase;
import com.itfromzero.order.domain.port.out.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 execute(String customerId, BigDecimal amount) {
Order newOrder = new Order(UUID.randomUUID(), customerId, amount);
return orderRepositoryPort.save(newOrder);
}
}
Architecture Essentials: The Dependency Rule
The core of Clean Architecture lies in the Dependency Rule: outer layers point inward; the core never points outward.
- Domain: The core of the system. Absolutely no annotations like
@Entity,@Table, or external libraries. The domain remains completely independent even if Spring Framework is swapped out. - Application (Use Cases): The system’s business scenarios. This layer orchestrates entities and ports, ensuring business logic executes in the correct sequence.
- Infrastructure: Houses Spring Boot 3, Hibernate, Kafka, and Redis. This layer acts as Adapters implementing the Ports defined by the Domain.
Registering Beans Without @Service
Since OrderService is completely free of Spring annotations, how does the container manage it? The answer is centralized configuration using Java Config in the Infrastructure layer:
package com.itfromzero.order.infrastructure.config;
import com.itfromzero.order.application.service.OrderService;
import com.itfromzero.order.domain.port.in.CreateOrderUseCase;
import com.itfromzero.order.domain.port.out.OrderRepositoryPort;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OrderBeanConfig {
@Bean
public CreateOrderUseCase createOrderUseCase(OrderRepositoryPort orderRepositoryPort) {
return new OrderService(orderRepositoryPort);
}
}
Optimizing Unit Tests: Zero Spring Context Startup
The biggest benefit of this architecture is test execution speed. Previously, developers often defaulted to @SpringBootTest. On each run, Spring had to load the entire ApplicationContext, taking 20 to 45 seconds for a simple test class.
With pure POJOs, all we need is JUnit 5 and Mockito. The entire test suite completes in under 0.05 seconds.
package com.itfromzero.order.application.service;
import com.itfromzero.order.domain.model.Order;
import com.itfromzero.order.domain.model.OrderStatus;
import com.itfromzero.order.domain.port.out.OrderRepositoryPort;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
private OrderRepositoryPort orderRepositoryPort;
private OrderService orderService;
@BeforeEach
void setUp() {
orderService = new OrderService(orderRepositoryPort);
}
@Test
@DisplayName("Should create order successfully when amount is valid")
void shouldCreateOrderSuccessfully() {
when(orderRepositoryPort.save(any(Order.class)))
.thenAnswer(invocation -> invocation.getArgument(0));
Order result = orderService.execute("cust-123", new BigDecimal("150000"));
assertThat(result).isNotNull();
assertThat(result.getCustomerId()).isEqualTo("cust-123");
assertThat(result.getTotalAmount()).isEqualByComparingTo("150000");
assertThat(result.getStatus()).isEqualTo(OrderStatus.CREATED);
verify(orderRepositoryPort, times(1)).save(any(Order.class));
}
@Test
@DisplayName("Should throw exception when order amount is zero or negative")
void shouldThrowExceptionWhenAmountIsInvalid() {
assertThatThrownBy(() -> orderService.execute("cust-123", BigDecimal.ZERO))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Order total amount must be greater than 0");
verifyNoInteractions(orderRepositoryPort);
}
}
No Docker, no in-memory database, no Spring Context. Our team’s suite of 250 business unit tests finishes in a blazing-fast 1.8 seconds on GitHub Actions.
3 Hard-Earned Lessons After 6 Months in Production
This pattern helped our 6-person team slash CI run times from 8 minutes down to 1 minute 15 seconds. Merge conflicts dropped by around 70%. That said, keep these three lessons in mind to avoid overcomplication:
1. Beware the Over-Engineering Trap
Clean Architecture comes at the cost of doubling the number of files. You must write Domain Models, JPA Entities, DTOs, along with a flurry of Mappers. If your module is just basic CRUD (like managing a lookup table of cities and provinces), stick to the traditional 3-tier architecture. Reserve Clean Architecture for modules with complex, frequently changing business rules.
2. Use MapStruct Instead of Manual Mapping
Manually writing dozens of conversion methods between OrderJpaEntity and Order makes it easy to miss fields during database schema updates. Let MapStruct generate the code at compile time:
@Mapper(componentModel = "spring")
public interface OrderEntityMapper {
OrderJpaEntity toJpaEntity(Order order);
Order toDomainModel(OrderJpaEntity entity);
}
3. Enforce Architectural Boundaries with ArchUnit
Under tight sprint deadlines, teammates might accidentally drop in @Autowired or import Spring packages into the domain layer. Let ArchUnit fail the build immediately if anyone violates architectural boundaries:
@Test
void domainLayerShouldNotDependOnSpring() {
noClasses()
.that().resideInAPackage("..domain..")
.should().dependOnClassesThat().resideInAPackage("org.springframework..")
.check(new ClassFileImporter().importPackages("com.itfromzero.order"));
}
