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.4allowed-tools: Read, Write, Edit, Bash, Glob, Grep5metadata:6 source: https://skillmd.com/skills/levalencia/clean-architecture7---89# Clean Architecture, Hexagonal Architecture & DDD for Spring Boot1011## Overview1213This 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.1415## When to Use1617- Architecting new Spring Boot applications with clear separation of concerns18- Refactoring tightly coupled code into testable, layered architectures19- Implementing domain logic independent of frameworks and infrastructure20- Designing ports and adapters for swappable implementations21- Applying Domain-Driven Design tactical patterns (entities, value objects, aggregates)22- Creating testable business logic without Spring context dependencies23- Trigger phrases: **"implement clean architecture"**, **"ports and adapters pattern"**, **"separate domain from infrastructure"**, **"hexagonal architecture Spring Boot"**, **"DDD aggregate design"**2425## Instructions2627### 1. Understand the Core Concepts2829#### Clean Architecture Layers (Dependency Rule)3031Dependencies flow inward. Inner layers know nothing about outer layers.3233| Layer | Responsibility | Spring Boot Equivalent |34|-------|---------------|----------------------|35| **Domain** | Entities, value objects, domain events, repository interfaces | `domain/` - no Spring annotations |36| **Application** | Use cases, application services, DTOs, ports | `application/` - @Service, @Transactional |37| **Infrastructure** | Frameworks, database, external APIs | `infrastructure/` - @Repository, @Entity |38| **Adapter** | Controllers, presenters, external gateways | `adapter/` - @RestController |3940#### Hexagonal Architecture (Ports & Adapters)4142- **Domain Core**: Pure Java business logic, no framework dependencies43- **Ports**: Interfaces defining contracts (driven and driving)44- **Adapters**: Concrete implementations (JPA, REST, messaging)4546#### Domain-Driven Design Tactical Patterns4748- **Entities**: Objects with identity and lifecycle (e.g., `Order`, `Customer`)49- **Value Objects**: Immutable, defined by attributes (e.g., `Money`, `Email`)50- **Aggregates**: Consistency boundary with root entity51- **Domain Events**: Capture significant business occurrences52- **Repositories**: Persistence abstraction, implemented in infrastructure5354### 2. Organize Package Structure5556Follow this feature-based package organization:5758```59com.example.order/60├── domain/61│ ├── model/ # Entities, value objects62│ ├── event/ # Domain events63│ ├── repository/ # Repository interfaces (ports)64│ └── exception/ # Domain exceptions65├── application/66│ ├── port/in/ # Driving ports (use case interfaces)67│ ├── port/out/ # Driven ports (external service interfaces)68│ ├── service/ # Application services69│ └── dto/ # Request/response DTOs70├── infrastructure/71│ ├── persistence/ # JPA entities, repository adapters72│ └── external/ # External service adapters73└── adapter/74 └── rest/ # REST controllers75```7677### 3. Implement the Domain Layer (Framework-Free)7879The domain layer must have zero dependencies on Spring or any framework.8081- Use Java records for immutable value objects with built-in validation82- Place business logic in entities, not services (Rich Domain Model)83- Define repository interfaces (ports) in the domain layer84- Use strongly-typed IDs to prevent ID confusion85- Implement domain events for decoupling side effects86- Use factory methods for entity creation to enforce invariants8788### 4. Implement the Application Layer8990- Create use case interfaces (driving ports) in `application/port/in/`91- Create external service interfaces (driven ports) in `application/port/out/`92- Implement application services with `@Service` and `@Transactional`93- Use DTOs for request/response, separate from domain models94- Publish domain events after successful operations9596### 5. Implement the Infrastructure Layer (Adapters)9798- Create JPA entities in `infrastructure/persistence/`99- Implement repository adapters that map between domain and JPA entities100- Use MapStruct or manual mappers for domain-JPA conversion101- Configure conditional beans for swappable implementations102- Keep infrastructure concerns isolated from domain logic103104### 6. Implement the Adapter Layer (REST)105106- Create REST controllers in `adapter/rest/`107- Inject use case interfaces, not implementations108- Use Bean Validation on DTOs109- Return proper HTTP status codes and responses110- Handle exceptions with global exception handlers111112### 7. Apply Best Practices1131141. **Dependency Rule**: Domain has zero dependencies on Spring or other frameworks1152. **Immutable Value Objects**: Use Java records for value objects with built-in validation1163. **Rich Domain Models**: Place business logic in entities, not services1174. **Repository Pattern**: Domain defines interface, infrastructure implements1185. **Domain Events**: Decouple side effects from primary operations1196. **Constructor Injection**: Mandatory dependencies via final fields1207. **DTO Mapping**: Separate domain models from API contracts1218. **Transaction Boundaries**: Place @Transactional in application services122123### 8. Write Tests124125- **Domain Tests**: Pure unit tests without Spring context, fast execution126- **Application Tests**: Unit tests with mocked ports using Mockito127- **Infrastructure Tests**: Integration tests with @DataJpaTest and Testcontainers128- **Adapter Tests**: Controller tests with @WebMvcTest129130## Examples131132### Example 1: Domain Layer - Entity with Domain Events133134```java135// domain/model/Order.java136public class Order {137 private final OrderId id;138 private final List<OrderItem> items;139 private Money total;140 private OrderStatus status;141 private final List<DomainEvent> domainEvents = new ArrayList<>();142143 private Order(OrderId id, List<OrderItem> items) {144 this.id = id;145 this.items = new ArrayList<>(items);146 this.status = OrderStatus.PENDING;147 calculateTotal();148 }149150 public static Order create(List<OrderItem> items) {151 validateItems(items);152 Order order = new Order(OrderId.generate(), items);153 order.domainEvents.add(new OrderCreatedEvent(order.id, order.total));154 return order;155 }156157 public void confirm() {158 if (status != OrderStatus.PENDING) {159 throw new DomainException("Only pending orders can be confirmed");160 }161 this.status = OrderStatus.CONFIRMED;162 }163164 public List<DomainEvent> getDomainEvents() {165 return List.copyOf(domainEvents);166 }167168 public void clearDomainEvents() {169 domainEvents.clear();170 }171}172```173174### Example 2: Domain Layer - Value Object with Validation175176```java177// domain/model/Money.java (Value Object)178public record Money(BigDecimal amount, Currency currency) {179 public Money {180 if (amount.compareTo(BigDecimal.ZERO) < 0) {181 throw new DomainException("Amount cannot be negative");182 }183 }184185 public static Money zero() {186 return new Money(BigDecimal.ZERO, Currency.getInstance("EUR"));187 }188189 public Money add(Money other) {190 if (!this.currency.equals(other.currency)) {191 throw new DomainException("Currency mismatch");192 }193 return new Money(this.amount.add(other.amount), this.currency);194 }195}196```197198### Example 3: Domain Layer - Repository Port199200```java201// domain/repository/OrderRepository.java (Port)202public interface OrderRepository {203 Order save(Order order);204 Optional<Order> findById(OrderId id);205}206```207208### Example 4: Application Layer - Use Case and Service209210```java211// application/port/in/CreateOrderUseCase.java212public interface CreateOrderUseCase {213 OrderResponse createOrder(CreateOrderRequest request);214}215216// application/dto/CreateOrderRequest.java217public record CreateOrderRequest(218 @NotNull UUID customerId,219 @NotEmpty List<OrderItemRequest> items220) {}221222// application/service/OrderService.java223@Service224@RequiredArgsConstructor225@Transactional226public class OrderService implements CreateOrderUseCase {227 private final OrderRepository orderRepository;228 private final PaymentGateway paymentGateway;229 private final DomainEventPublisher eventPublisher;230231 @Override232 public OrderResponse createOrder(CreateOrderRequest request) {233 List<OrderItem> items = mapItems(request.items());234 Order order = Order.create(items);235236 PaymentResult payment = paymentGateway.charge(order.getTotal());237 if (!payment.successful()) {238 throw new PaymentFailedException("Payment failed");239 }240241 order.confirm();242 Order saved = orderRepository.save(order);243 publishEvents(order);244245 return OrderMapper.toResponse(saved);246 }247248 private void publishEvents(Order order) {249 order.getDomainEvents().forEach(eventPublisher::publish);250 order.clearDomainEvents();251 }252}253```254255### Example 5: Infrastructure Layer - JPA Entity and Adapter256257```java258// infrastructure/persistence/OrderJpaEntity.java259@Entity260@Table(name = "orders")261public class OrderJpaEntity {262 @Id263 private UUID id;264 @Enumerated(EnumType.STRING)265 private OrderStatus status;266 private BigDecimal totalAmount;267 @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)268 private List<OrderItemJpaEntity> items;269}270271// infrastructure/persistence/OrderRepositoryAdapter.java272@Component273@RequiredArgsConstructor274public class OrderRepositoryAdapter implements OrderRepository {275 private final OrderJpaRepository jpaRepository;276 private final OrderJpaMapper mapper;277278 @Override279 public Order save(Order order) {280 OrderJpaEntity entity = mapper.toEntity(order);281 return mapper.toDomain(jpaRepository.save(entity));282 }283284 @Override285 public Optional<Order> findById(OrderId id) {286 return jpaRepository.findById(id.value()).map(mapper::toDomain);287 }288}289```290291### Example 6: Adapter Layer - REST Controller292293```java294// adapter/rest/OrderController.java295@RestController296@RequestMapping("/api/orders")297@RequiredArgsConstructor298public class OrderController {299 private final CreateOrderUseCase createOrderUseCase;300301 @PostMapping302 public ResponseEntity<OrderResponse> createOrder(303 @Valid @RequestBody CreateOrderRequest request) {304 OrderResponse response = createOrderUseCase.createOrder(request);305 URI location = ServletUriComponentsBuilder306 .fromCurrentRequest()307 .path("/{id}")308 .buildAndExpand(response.id())309 .toUri();310 return ResponseEntity.created(location).body(response);311 }312}313```314315### Example 7: Domain Tests (No Spring Context)316317```java318class OrderTest {319 @Test320 void shouldCreateOrderWithValidItems() {321 List<OrderItem> items = List.of(322 new OrderItem(new ProductId(UUID.randomUUID()), 2, new Money("10.00", EUR))323 );324325 Order order = Order.create(items);326327 assertThat(order.getStatus()).isEqualTo(OrderStatus.PENDING);328 assertThat(order.getDomainEvents()).hasSize(1);329 }330}331```332333### Example 8: Application Tests (Unit with Mocks)334335```java336@ExtendWith(MockitoExtension.class)337class OrderServiceTest {338 @Mock OrderRepository orderRepository;339 @Mock PaymentGateway paymentGateway;340 @Mock DomainEventPublisher eventPublisher;341342 @InjectMocks OrderService orderService;343344 @Test345 void shouldCreateAndConfirmOrder() {346 when(paymentGateway.charge(any())).thenReturn(new PaymentResult(true, "tx-123"));347 when(orderRepository.save(any())).thenAnswer(i -> i.getArgument(0));348349 OrderResponse response = orderService.createOrder(createRequest());350351 assertThat(response.status()).isEqualTo(OrderStatus.CONFIRMED);352 verify(eventPublisher).publish(any(OrderCreatedEvent.class));353 }354}355```356357## Best Practices3583591. **Dependency Rule**: Domain has zero dependencies on Spring or other frameworks - this is the most critical principle3602. **Immutable Value Objects**: Use Java records for value objects with built-in validation in compact constructors3613. **Rich Domain Models**: Place business logic in entities, not services - avoid anemic domain models3624. **Repository Pattern**: Domain defines interface, infrastructure implements - never the reverse3635. **Domain Events**: Decouple side effects from primary operations using event-driven patterns3646. **Constructor Injection**: Mandatory dependencies via final fields with Lombok @RequiredArgsConstructor3657. **DTO Mapping**: Separate domain models from API contracts - never expose entities directly3668. **Transaction Boundaries**: Place @Transactional in application services, never in domain layer3679. **Factory Methods**: Use static factory methods like `Entity.create()` for entity construction with invariant enforcement36810. **Separate JPA Entities**: Keep domain entities separate from JPA entities with mappers between them369370## Constraints and Warnings371372### Critical Constraints373374- **Domain Layer Purity**: Never add Spring annotations (`@Entity`, `@Autowired`, `@Component`) to domain classes375- **Dependency Direction**: Dependencies must only point inward (domain <- application <- infrastructure/adapter)376- **Framework Isolation**: All framework-specific code must stay in infrastructure and adapter layers377378### Common Pitfalls to Avoid379380- **Anemic Domain Model**: Entities with only getters/setters, logic in services - place business logic in entities381- **Framework Leakage**: `@Entity`, `@Autowired` in domain layer - keep domain framework-free382- **Lazy Loading Issues**: Exposing JPA entities through domain model - use mappers to convert383- **Circular Dependencies**: Between domain aggregates - use IDs instead of direct references384- **Missing Domain Events**: Direct service calls instead of events for cross-aggregate communication385- **Repository Misplacement**: Defining repository interfaces in infrastructure - they belong in domain386- **DTO Bypass**: Exposing domain entities directly in API - always use DTOs for external contracts387388### Performance Considerations389390- Separate JPA entities from domain models to avoid lazy loading issues391- Use read-only transactions for query operations392- Consider CQRS for complex read/write scenarios393394## References395396- `references/java-clean-architecture.md` - Java-specific patterns (records, sealed classes, strongly-typed IDs)397- `references/spring-boot-implementation.md` - Spring Boot integration (DI patterns, JPA mapping, transaction management)