Clean Architecture, Hexagonal Architecture & DDD for Spring Boot
Overview
This skill provides comprehensive guidance for implementing Clean Architecture, Hexagonal Architecture (Ports & Adapters), and Domain-Driven Design tactical patterns in Java 21+ Spring Boot 3.5+ applications. It ensures clear separation of concerns, framework-independent domain logic, and highly testable codebases through proper layering and dependency management.
When to Use
- Architecting new Spring Boot applications with clear separation of concerns
- Refactoring tightly coupled code into testable, layered architectures
- Implementing domain logic independent of frameworks and infrastructure
- Designing ports and adapters for swappable implementations
- Applying Domain-Driven Design tactical patterns (entities, value objects, aggregates)
- Creating testable business logic without Spring context dependencies
- Trigger phrases: "implement clean architecture", "ports and adapters pattern", "separate domain from infrastructure", "hexagonal architecture Spring Boot", "DDD aggregate design"
Instructions
1. Understand the Core Concepts
Clean Architecture Layers (Dependency Rule)
Dependencies flow inward. Inner layers know nothing about outer layers.
| Layer |
Responsibility |
Spring Boot Equivalent |
| Domain |
Entities, value objects, domain events, repository interfaces |
domain/ - no Spring annotations |
| Application |
Use cases, application services, DTOs, ports |
application/ - @Service, @Transactional |
| Infrastructure |
Frameworks, database, external APIs |
infrastructure/ - @Repository, @Entity |
| Adapter |
Controllers, presenters, external gateways |
adapter/ - @RestController |
Hexagonal Architecture (Ports & Adapters)
- Domain Core: Pure Java business logic, no framework dependencies
- Ports: Interfaces defining contracts (driven and driving)
- Adapters: Concrete implementations (JPA, REST, messaging)
Domain-Driven Design Tactical Patterns
- Entities: Objects with identity and lifecycle (e.g.,
Order, Customer)
- Value Objects: Immutable, defined by attributes (e.g.,
Money, Email)
- Aggregates: Consistency boundary with root entity
- Domain Events: Capture significant business occurrences
- Repositories: Persistence abstraction, implemented in infrastructure
2. Organize Package Structure
Follow this feature-based package organization:
com.example.order/
├── domain/
│ ├── model/ # Entities, value objects
│ ├── event/ # Domain events
│ ├── repository/ # Repository interfaces (ports)
│ └── exception/ # Domain exceptions
├── application/
│ ├── port/in/ # Driving ports (use case interfaces)
│ ├── port/out/ # Driven ports (external service interfaces)
│ ├── service/ # Application services
│ └── dto/ # Request/response DTOs
├── infrastructure/
│ ├── persistence/ # JPA entities, repository adapters
│ └── external/ # External service adapters
└── adapter/
└── rest/ # REST controllers
3. Implement the Domain Layer (Framework-Free)
The domain layer must have zero dependencies on Spring or any framework.
- Use Java records for immutable value objects with built-in validation
- Place business logic in entities, not services (Rich Domain Model)
- Define repository interfaces (ports) in the domain layer
- Use strongly-typed IDs to prevent ID confusion
- Implement domain events for decoupling side effects
- Use factory methods for entity creation to enforce invariants
4. Implement the Application Layer
- Create use case interfaces (driving ports) in
application/port/in/
- Create external service interfaces (driven ports) in
application/port/out/
- Implement application services with
@Service and @Transactional
- Use DTOs for request/response, separate from domain models
- Publish domain events after successful operations
5. Implement the Infrastructure Layer (Adapters)
- Create JPA entities in
infrastructure/persistence/
- Implement repository adapters that map between domain and JPA entities
- Use MapStruct or manual mappers for domain-JPA conversion
- Configure conditional beans for swappable implementations
- Keep infrastructure concerns isolated from domain logic
6. Implement the Adapter Layer (REST)
- Create REST controllers in
adapter/rest/
- Inject use case interfaces, not implementations
- Use Bean Validation on DTOs
- Return proper HTTP status codes and responses
- Handle exceptions with global exception handlers
7. Apply Best Practices
- Dependency Rule: Domain has zero dependencies on Spring or other frameworks
- Immutable Value Objects: Use Java records for value objects with built-in validation
- Rich Domain Models: Place business logic in entities, not services
- Repository Pattern: Domain defines interface, infrastructure implements
- Domain Events: Decouple side effects from primary operations
- Constructor Injection: Mandatory dependencies via final fields
- DTO Mapping: Separate domain models from API contracts
- Transaction Boundaries: Place @Transactional in application services
8. Write Tests
- Domain Tests: Pure unit tests without Spring context, fast execution
- Application Tests: Unit tests with mocked ports using Mockito
- Infrastructure Tests: Integration tests with @DataJpaTest and Testcontainers
- Adapter Tests: Controller tests with @WebMvcTest
Examples
Example 1: Domain Layer - Entity with Domain Events
// domain/model/Order.java
public class Order {
private final OrderId id;
private final List<OrderItem> items;
private Money total;
private OrderStatus status;
private final List<DomainEvent> domainEvents = new ArrayList<>();
private Order(OrderId id, List<OrderItem> items) {
this.id = id;
this.items = new ArrayList<>(items);
this.status = OrderStatus.PENDING;
calculateTotal();
}
public static Order create(List<OrderItem> items) {
validateItems(items);
Order order = new Order(OrderId.generate(), items);
order.domainEvents.add(new OrderCreatedEvent(order.id, order.total));
return order;
}
public void confirm() {
if (status != OrderStatus.PENDING) {
throw new DomainException("Only pending orders can be confirmed");
}
this.status = OrderStatus.CONFIRMED;
}
public List<DomainEvent> getDomainEvents() {
return List.copyOf(domainEvents);
}
public void clearDomainEvents() {
domainEvents.clear();
}
}
Example 2: Domain Layer - Value Object with Validation
// domain/model/Money.java (Value Object)
public record Money(BigDecimal amount, Currency currency) {
public Money {
if (amount.compareTo(BigDecimal.ZERO) < 0) {
throw new DomainException("Amount cannot be negative");
}
}
public static Money zero() {
return new Money(BigDecimal.ZERO, Currency.getInstance("EUR"));
}
public Money add(Money other) {
if (!this.currency.equals(other.currency)) {
throw new DomainException("Currency mismatch");
}
return new Money(this.amount.add(other.amount), this.currency);
}
}
Example 3: Domain Layer - Repository Port
// domain/repository/OrderRepository.java (Port)
public interface OrderRepository {
Order save(Order order);
Optional<Order> findById(OrderId id);
}
Example 4: Application Layer - Use Case and Service
// application/port/in/CreateOrderUseCase.java
public interface CreateOrderUseCase {
OrderResponse createOrder(CreateOrderRequest request);
}
// application/dto/CreateOrderRequest.java
public record CreateOrderRequest(
@NotNull UUID customerId,
@NotEmpty List<OrderItemRequest> items
) {}
// application/service/OrderService.java
@Service
@RequiredArgsConstructor
@Transactional
public class OrderService implements CreateOrderUseCase {
private final OrderRepository orderRepository;
private final PaymentGateway paymentGateway;
private final DomainEventPublisher eventPublisher;
@Override
public OrderResponse createOrder(CreateOrderRequest request) {
List<OrderItem> items = mapItems(request.items());
Order order = Order.create(items);
PaymentResult payment = paymentGateway.charge(order.getTotal());
if (!payment.successful()) {
throw new PaymentFailedException("Payment failed");
}
order.confirm();
Order saved = orderRepository.save(order);
publishEvents(order);
return OrderMapper.toResponse(saved);
}
private void publishEvents(Order order) {
order.getDomainEvents().forEach(eventPublisher::publish);
order.clearDomainEvents();
}
}
Example 5: Infrastructure Layer - JPA Entity and Adapter
// infrastructure/persistence/OrderJpaEntity.java
@Entity
@Table(name = "orders")
public class OrderJpaEntity {
@Id
private UUID id;
@Enumerated(EnumType.STRING)
private OrderStatus status;
private BigDecimal totalAmount;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderItemJpaEntity> items;
}
// infrastructure/persistence/OrderRepositoryAdapter.java
@Component
@RequiredArgsConstructor
public class OrderRepositoryAdapter implements OrderRepository {
private final OrderJpaRepository jpaRepository;
private final OrderJpaMapper mapper;
@Override
public Order save(Order order) {
OrderJpaEntity entity = mapper.toEntity(order);
return mapper.toDomain(jpaRepository.save(entity));
}
@Override
public Optional<Order> findById(OrderId id) {
return jpaRepository.findById(id.value()).map(mapper::toDomain);
}
}
Example 6: Adapter Layer - REST Controller
// adapter/rest/OrderController.java
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderController {
private final CreateOrderUseCase createOrderUseCase;
@PostMapping
public ResponseEntity<OrderResponse> createOrder(
@Valid @RequestBody CreateOrderRequest request) {
OrderResponse response = createOrderUseCase.createOrder(request);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(response.id())
.toUri();
return ResponseEntity.created(location).body(response);
}
}
Example 7: Domain Tests (No Spring Context)
class OrderTest {
@Test
void shouldCreateOrderWithValidItems() {
List<OrderItem> items = List.of(
new OrderItem(new ProductId(UUID.randomUUID()), 2, new Money("10.00", EUR))
);
Order order = Order.create(items);
assertThat(order.getStatus()).isEqualTo(OrderStatus.PENDING);
assertThat(order.getDomainEvents()).hasSize(1);
}
}
Example 8: Application Tests (Unit with Mocks)
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock OrderRepository orderRepository;
@Mock PaymentGateway paymentGateway;
@Mock DomainEventPublisher eventPublisher;
@InjectMocks OrderService orderService;
@Test
void shouldCreateAndConfirmOrder() {
when(paymentGateway.charge(any())).thenReturn(new PaymentResult(true, "tx-123"));
when(orderRepository.save(any())).thenAnswer(i -> i.getArgument(0));
OrderResponse response = orderService.createOrder(createRequest());
assertThat(response.status()).isEqualTo(OrderStatus.CONFIRMED);
verify(eventPublisher).publish(any(OrderCreatedEvent.class));
}
}
Best Practices
- Dependency Rule: Domain has zero dependencies on Spring or other frameworks - this is the most critical principle
- Immutable Value Objects: Use Java records for value objects with built-in validation in compact constructors
- Rich Domain Models: Place business logic in entities, not services - avoid anemic domain models
- Repository Pattern: Domain defines interface, infrastructure implements - never the reverse
- Domain Events: Decouple side effects from primary operations using event-driven patterns
- Constructor Injection: Mandatory dependencies via final fields with Lombok @RequiredArgsConstructor
- DTO Mapping: Separate domain models from API contracts - never expose entities directly
- Transaction Boundaries: Place @Transactional in application services, never in domain layer
- Factory Methods: Use static factory methods like
Entity.create() for entity construction with invariant enforcement
- Separate JPA Entities: Keep domain entities separate from JPA entities with mappers between them
Constraints and Warnings
Critical Constraints
- Domain Layer Purity: Never add Spring annotations (
@Entity, @Autowired, @Component) to domain classes
- Dependency Direction: Dependencies must only point inward (domain <- application <- infrastructure/adapter)
- Framework Isolation: All framework-specific code must stay in infrastructure and adapter layers
Common Pitfalls to Avoid
- Anemic Domain Model: Entities with only getters/setters, logic in services - place business logic in entities
- Framework Leakage:
@Entity, @Autowired in domain layer - keep domain framework-free
- Lazy Loading Issues: Exposing JPA entities through domain model - use mappers to convert
- Circular Dependencies: Between domain aggregates - use IDs instead of direct references
- Missing Domain Events: Direct service calls instead of events for cross-aggregate communication
- Repository Misplacement: Defining repository interfaces in infrastructure - they belong in domain
- DTO Bypass: Exposing domain entities directly in API - always use DTOs for external contracts
Performance Considerations
- Separate JPA entities from domain models to avoid lazy loading issues
- Use read-only transactions for query operations
- Consider CQRS for complex read/write scenarios
References
references/java-clean-architecture.md - Java-specific patterns (records, sealed classes, strongly-typed IDs)
references/spring-boot-implementation.md - Spring Boot integration (DI patterns, JPA mapping, transaction management)
1---2name: clean-architecture3description: Provides implementation patterns for Clean Architecture, Hexagonal Architecture (Ports & Adapters), and Domain-Driven Design in Java 21+ Spring Boot 3.5+ applications. Use when structuring layered architectures, separating domain logic from frameworks, implementing ports and adapters, creating entities/value objects/aggregates, or refactoring monolithic codebases for testability and maintainability.4---56# Clean Architecture, Hexagonal Architecture & DDD for Spring Boot78## Overview910This skill provides comprehensive guidance for implementing Clean Architecture, Hexagonal Architecture (Ports & Adapters), and Domain-Driven Design tactical patterns in Java 21+ Spring Boot 3.5+ applications. It ensures clear separation of concerns, framework-independent domain logic, and highly testable codebases through proper layering and dependency management.1112## When to Use1314- Architecting new Spring Boot applications with clear separation of concerns15- Refactoring tightly coupled code into testable, layered architectures16- Implementing domain logic independent of frameworks and infrastructure17- Designing ports and adapters for swappable implementations18- Applying Domain-Driven Design tactical patterns (entities, value objects, aggregates)19- Creating testable business logic without Spring context dependencies20- Trigger phrases: **"implement clean architecture"**, **"ports and adapters pattern"**, **"separate domain from infrastructure"**, **"hexagonal architecture Spring Boot"**, **"DDD aggregate design"**2122## Instructions2324### 1. Understand the Core Concepts2526#### Clean Architecture Layers (Dependency Rule)2728Dependencies flow inward. Inner layers know nothing about outer layers.2930| Layer | Responsibility | Spring Boot Equivalent |31|-------|---------------|----------------------|32| **Domain** | Entities, value objects, domain events, repository interfaces | `domain/` - no Spring annotations |33| **Application** | Use cases, application services, DTOs, ports | `application/` - @Service, @Transactional |34| **Infrastructure** | Frameworks, database, external APIs | `infrastructure/` - @Repository, @Entity |35| **Adapter** | Controllers, presenters, external gateways | `adapter/` - @RestController |3637#### Hexagonal Architecture (Ports & Adapters)3839- **Domain Core**: Pure Java business logic, no framework dependencies40- **Ports**: Interfaces defining contracts (driven and driving)41- **Adapters**: Concrete implementations (JPA, REST, messaging)4243#### Domain-Driven Design Tactical Patterns4445- **Entities**: Objects with identity and lifecycle (e.g., `Order`, `Customer`)46- **Value Objects**: Immutable, defined by attributes (e.g., `Money`, `Email`)47- **Aggregates**: Consistency boundary with root entity48- **Domain Events**: Capture significant business occurrences49- **Repositories**: Persistence abstraction, implemented in infrastructure5051### 2. Organize Package Structure5253Follow this feature-based package organization:5455```56com.example.order/57├── domain/58│ ├── model/ # Entities, value objects59│ ├── event/ # Domain events60│ ├── repository/ # Repository interfaces (ports)61│ └── exception/ # Domain exceptions62├── application/63│ ├── port/in/ # Driving ports (use case interfaces)64│ ├── port/out/ # Driven ports (external service interfaces)65│ ├── service/ # Application services66│ └── dto/ # Request/response DTOs67├── infrastructure/68│ ├── persistence/ # JPA entities, repository adapters69│ └── external/ # External service adapters70└── adapter/71 └── rest/ # REST controllers72```7374### 3. Implement the Domain Layer (Framework-Free)7576The domain layer must have zero dependencies on Spring or any framework.7778- Use Java records for immutable value objects with built-in validation79- Place business logic in entities, not services (Rich Domain Model)80- Define repository interfaces (ports) in the domain layer81- Use strongly-typed IDs to prevent ID confusion82- Implement domain events for decoupling side effects83- Use factory methods for entity creation to enforce invariants8485### 4. Implement the Application Layer8687- Create use case interfaces (driving ports) in `application/port/in/`88- Create external service interfaces (driven ports) in `application/port/out/`89- Implement application services with `@Service` and `@Transactional`90- Use DTOs for request/response, separate from domain models91- Publish domain events after successful operations9293### 5. Implement the Infrastructure Layer (Adapters)9495- Create JPA entities in `infrastructure/persistence/`96- Implement repository adapters that map between domain and JPA entities97- Use MapStruct or manual mappers for domain-JPA conversion98- Configure conditional beans for swappable implementations99- Keep infrastructure concerns isolated from domain logic100101### 6. Implement the Adapter Layer (REST)102103- Create REST controllers in `adapter/rest/`104- Inject use case interfaces, not implementations105- Use Bean Validation on DTOs106- Return proper HTTP status codes and responses107- Handle exceptions with global exception handlers108109### 7. Apply Best Practices1101111. **Dependency Rule**: Domain has zero dependencies on Spring or other frameworks1122. **Immutable Value Objects**: Use Java records for value objects with built-in validation1133. **Rich Domain Models**: Place business logic in entities, not services1144. **Repository Pattern**: Domain defines interface, infrastructure implements1155. **Domain Events**: Decouple side effects from primary operations1166. **Constructor Injection**: Mandatory dependencies via final fields1177. **DTO Mapping**: Separate domain models from API contracts1188. **Transaction Boundaries**: Place @Transactional in application services119120### 8. Write Tests121122- **Domain Tests**: Pure unit tests without Spring context, fast execution123- **Application Tests**: Unit tests with mocked ports using Mockito124- **Infrastructure Tests**: Integration tests with @DataJpaTest and Testcontainers125- **Adapter Tests**: Controller tests with @WebMvcTest126127## Examples128129### Example 1: Domain Layer - Entity with Domain Events130131```java132// domain/model/Order.java133public class Order {134 private final OrderId id;135 private final List<OrderItem> items;136 private Money total;137 private OrderStatus status;138 private final List<DomainEvent> domainEvents = new ArrayList<>();139140 private Order(OrderId id, List<OrderItem> items) {141 this.id = id;142 this.items = new ArrayList<>(items);143 this.status = OrderStatus.PENDING;144 calculateTotal();145 }146147 public static Order create(List<OrderItem> items) {148 validateItems(items);149 Order order = new Order(OrderId.generate(), items);150 order.domainEvents.add(new OrderCreatedEvent(order.id, order.total));151 return order;152 }153154 public void confirm() {155 if (status != OrderStatus.PENDING) {156 throw new DomainException("Only pending orders can be confirmed");157 }158 this.status = OrderStatus.CONFIRMED;159 }160161 public List<DomainEvent> getDomainEvents() {162 return List.copyOf(domainEvents);163 }164165 public void clearDomainEvents() {166 domainEvents.clear();167 }168}169```170171### Example 2: Domain Layer - Value Object with Validation172173```java174// domain/model/Money.java (Value Object)175public record Money(BigDecimal amount, Currency currency) {176 public Money {177 if (amount.compareTo(BigDecimal.ZERO) < 0) {178 throw new DomainException("Amount cannot be negative");179 }180 }181182 public static Money zero() {183 return new Money(BigDecimal.ZERO, Currency.getInstance("EUR"));184 }185186 public Money add(Money other) {187 if (!this.currency.equals(other.currency)) {188 throw new DomainException("Currency mismatch");189 }190 return new Money(this.amount.add(other.amount), this.currency);191 }192}193```194195### Example 3: Domain Layer - Repository Port196197```java198// domain/repository/OrderRepository.java (Port)199public interface OrderRepository {200 Order save(Order order);201 Optional<Order> findById(OrderId id);202}203```204205### Example 4: Application Layer - Use Case and Service206207```java208// application/port/in/CreateOrderUseCase.java209public interface CreateOrderUseCase {210 OrderResponse createOrder(CreateOrderRequest request);211}212213// application/dto/CreateOrderRequest.java214public record CreateOrderRequest(215 @NotNull UUID customerId,216 @NotEmpty List<OrderItemRequest> items217) {}218219// application/service/OrderService.java220@Service221@RequiredArgsConstructor222@Transactional223public class OrderService implements CreateOrderUseCase {224 private final OrderRepository orderRepository;225 private final PaymentGateway paymentGateway;226 private final DomainEventPublisher eventPublisher;227228 @Override229 public OrderResponse createOrder(CreateOrderRequest request) {230 List<OrderItem> items = mapItems(request.items());231 Order order = Order.create(items);232233 PaymentResult payment = paymentGateway.charge(order.getTotal());234 if (!payment.successful()) {235 throw new PaymentFailedException("Payment failed");236 }237238 order.confirm();239 Order saved = orderRepository.save(order);240 publishEvents(order);241242 return OrderMapper.toResponse(saved);243 }244245 private void publishEvents(Order order) {246 order.getDomainEvents().forEach(eventPublisher::publish);247 order.clearDomainEvents();248 }249}250```251252### Example 5: Infrastructure Layer - JPA Entity and Adapter253254```java255// infrastructure/persistence/OrderJpaEntity.java256@Entity257@Table(name = "orders")258public class OrderJpaEntity {259 @Id260 private UUID id;261 @Enumerated(EnumType.STRING)262 private OrderStatus status;263 private BigDecimal totalAmount;264 @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)265 private List<OrderItemJpaEntity> items;266}267268// infrastructure/persistence/OrderRepositoryAdapter.java269@Component270@RequiredArgsConstructor271public class OrderRepositoryAdapter implements OrderRepository {272 private final OrderJpaRepository jpaRepository;273 private final OrderJpaMapper mapper;274275 @Override276 public Order save(Order order) {277 OrderJpaEntity entity = mapper.toEntity(order);278 return mapper.toDomain(jpaRepository.save(entity));279 }280281 @Override282 public Optional<Order> findById(OrderId id) {283 return jpaRepository.findById(id.value()).map(mapper::toDomain);284 }285}286```287288### Example 6: Adapter Layer - REST Controller289290```java291// adapter/rest/OrderController.java292@RestController293@RequestMapping("/api/orders")294@RequiredArgsConstructor295public class OrderController {296 private final CreateOrderUseCase createOrderUseCase;297298 @PostMapping299 public ResponseEntity<OrderResponse> createOrder(300 @Valid @RequestBody CreateOrderRequest request) {301 OrderResponse response = createOrderUseCase.createOrder(request);302 URI location = ServletUriComponentsBuilder303 .fromCurrentRequest()304 .path("/{id}")305 .buildAndExpand(response.id())306 .toUri();307 return ResponseEntity.created(location).body(response);308 }309}310```311312### Example 7: Domain Tests (No Spring Context)313314```java315class OrderTest {316 @Test317 void shouldCreateOrderWithValidItems() {318 List<OrderItem> items = List.of(319 new OrderItem(new ProductId(UUID.randomUUID()), 2, new Money("10.00", EUR))320 );321322 Order order = Order.create(items);323324 assertThat(order.getStatus()).isEqualTo(OrderStatus.PENDING);325 assertThat(order.getDomainEvents()).hasSize(1);326 }327}328```329330### Example 8: Application Tests (Unit with Mocks)331332```java333@ExtendWith(MockitoExtension.class)334class OrderServiceTest {335 @Mock OrderRepository orderRepository;336 @Mock PaymentGateway paymentGateway;337 @Mock DomainEventPublisher eventPublisher;338339 @InjectMocks OrderService orderService;340341 @Test342 void shouldCreateAndConfirmOrder() {343 when(paymentGateway.charge(any())).thenReturn(new PaymentResult(true, "tx-123"));344 when(orderRepository.save(any())).thenAnswer(i -> i.getArgument(0));345346 OrderResponse response = orderService.createOrder(createRequest());347348 assertThat(response.status()).isEqualTo(OrderStatus.CONFIRMED);349 verify(eventPublisher).publish(any(OrderCreatedEvent.class));350 }351}352```353354## Best Practices3553561. **Dependency Rule**: Domain has zero dependencies on Spring or other frameworks - this is the most critical principle3572. **Immutable Value Objects**: Use Java records for value objects with built-in validation in compact constructors3583. **Rich Domain Models**: Place business logic in entities, not services - avoid anemic domain models3594. **Repository Pattern**: Domain defines interface, infrastructure implements - never the reverse3605. **Domain Events**: Decouple side effects from primary operations using event-driven patterns3616. **Constructor Injection**: Mandatory dependencies via final fields with Lombok @RequiredArgsConstructor3627. **DTO Mapping**: Separate domain models from API contracts - never expose entities directly3638. **Transaction Boundaries**: Place @Transactional in application services, never in domain layer3649. **Factory Methods**: Use static factory methods like `Entity.create()` for entity construction with invariant enforcement36510. **Separate JPA Entities**: Keep domain entities separate from JPA entities with mappers between them366367## Constraints and Warnings368369### Critical Constraints370371- **Domain Layer Purity**: Never add Spring annotations (`@Entity`, `@Autowired`, `@Component`) to domain classes372- **Dependency Direction**: Dependencies must only point inward (domain <- application <- infrastructure/adapter)373- **Framework Isolation**: All framework-specific code must stay in infrastructure and adapter layers374375### Common Pitfalls to Avoid376377- **Anemic Domain Model**: Entities with only getters/setters, logic in services - place business logic in entities378- **Framework Leakage**: `@Entity`, `@Autowired` in domain layer - keep domain framework-free379- **Lazy Loading Issues**: Exposing JPA entities through domain model - use mappers to convert380- **Circular Dependencies**: Between domain aggregates - use IDs instead of direct references381- **Missing Domain Events**: Direct service calls instead of events for cross-aggregate communication382- **Repository Misplacement**: Defining repository interfaces in infrastructure - they belong in domain383- **DTO Bypass**: Exposing domain entities directly in API - always use DTOs for external contracts384385### Performance Considerations386387- Separate JPA entities from domain models to avoid lazy loading issues388- Use read-only transactions for query operations389- Consider CQRS for complex read/write scenarios390391## References392393- `references/java-clean-architecture.md` - Java-specific patterns (records, sealed classes, strongly-typed IDs)394- `references/spring-boot-implementation.md` - Spring Boot integration (DI patterns, JPA mapping, transaction management)