The domain layer is the heart of Clean Architecture: pure business logic, zero Spring, zero JPA, zero dependencies on the external world. Here live the entities that model your business — User, Article, Order, Payment — as immutable Java records. Each entity is accompanied by value objects (Email, Money, Slug) that validate data in the constructor. Business rules live in entity methods, not scattered across 10 different services. This article guides you step-by-step: how to model pure domain, implement value objects with validation, protect business invariants, and integrate ports and domain events. Target: Java developer who wants to transform a chaotic monolith into enterprise-maintainable codebase.
Introduction: Why Domain Layer Today (2026)?
In 2024-2026, 70% of Spring Boot projects suffer from "entity anemia": Entities with only getter/setter, business logic scattered between 20 services, zero testability. A true domain layer solves all this: concentrates business logic in one place, makes code testable without Spring context (1ms vs 500ms per test), and protects business rules from direct SQL access.
In Federico Calò's backend (real-world portfolio 1521 Java files), the domain layer was isolated from day one. Result: when you add new feature (RAG, dataset marketplace, Stripe integration), the code is already ready. Domain entities don't change; only infrastructure adapters change.
What is Domain Layer and Why Isolate It
The domain layer is the "core" of Clean Architecture. It contains:
- Entity: Models with unique identity (User, Article, Order). Identified by ID, not by value.
- Value Objects: Models without identity, identified by value (Email, Money, Slug, Color).
- Port (Interface): Contracts for interacting with the external world (Repository, EmailSender, PaymentGateway).
- Domain Service: Business logic that doesn't fit in an entity (e.g., CheckUserDuplicateService).
- Domain Event: Significant facts in the domain that other parts of the system listen to (UserRegisteredEvent, ArticlePublishedEvent).
Isolating it means: zero Spring imports, zero @Entity, zero JPA annotations, zero dependencies on external frameworks. The domain is 100% business, 0% infrastructure.
The Value of Isolating Domain
- Testability: Test entities without Spring context. A domain entity test runs in 1ms.
- Reusability: If tomorrow you use another persistence library, domain doesn't change.
- Business Protection: No one can bypass business rules via direct SQL. The only entry point is the domain entity.
- Predictable Refactoring: Change the infrastructure? Domain stays stable. Add new feature? Expand the domain, don't rewrite it.
Pure Entity with Java Records
Why Java Records (Java 21)
A Java record is an immutable class, concise, perfect for modeling domain entities. Zero boilerplate (no getter/setter/equals/hashCode/toString), but full business logic.
Example: User Entity
// Domain Layer: Pure entity, immutable, zero Spring
public record User(
UserId id, // Value Object for identity
Email email, // Value Object
String hashedPassword, // primitive: never store plaintext
UserName name, // Value Object
PremiumStatus premiumStatus, // Domain enum
ZonedDateTime createdAt,
ZonedDateTime lastLoginAt // nullable
) {
// Compact constructor: validation in constructor
public User {
Objects.requireNonNull(id, "UserId cannot be null");
Objects.requireNonNull(email, "Email cannot be null");
Objects.requireNonNull(hashedPassword, "Password cannot be null");
Objects.requireNonNull(name, "Name cannot be null");
Objects.requireNonNull(createdAt, "CreatedAt cannot be null");
}
// Business logic: domain methods
public boolean isPasswordValid(String plainPassword) {
return BCrypt.checkpw(plainPassword, hashedPassword);
}
public boolean isPremium() {
return premiumStatus == PremiumStatus.ACTIVE;
}
public User upgradeToPremiun() {
// Create new User with updated premiumStatus (immutability)
return new User(
this.id,
this.email,
this.hashedPassword,
this.name,
PremiumStatus.ACTIVE, // Update
this.createdAt,
this.lastLoginAt
);
}
public void recordLogin() {
// ERROR: record has no setter. To update, return new entity.
// this.lastLoginAt = ZonedDateTime.now(); // NO! Won't compile
}
public User withLastLogin(ZonedDateTime lastLogin) {
return new User(
this.id,
this.email,
this.hashedPassword,
this.name,
this.premiumStatus,
this.createdAt,
lastLogin // Update
);
}
// Factory method
public static User register(Email email, String hashedPassword, UserName name) {
return new User(
UserId.generate(),
email,
hashedPassword,
name,
PremiumStatus.FREE,
ZonedDateTime.now(ZoneId.of("UTC")),
null
);
}
}
// Domain enum
public enum PremiumStatus {
FREE, ACTIVE, SUSPENDED;
}
Value Objects: Constructor-Based Validation
Email Value Object
// Value Object: Immutable Email
public record Email(String value) {
// Compact constructor: validation
public Email {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Email cannot be empty");
}
// RFC 5322 simplified
if (!value.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$")) {
throw new IllegalArgumentException("Invalid email: " + value);
}
// Normalize
value = value.toLowerCase();
}
@Override
public String toString() {
return value;
}
// Two Email("test@example.com") are identical (value-based equality)
}
Money Value Object (with business logic)
// Value Object: Money with currency safety
public record Money(BigDecimal amount, Currency currency) {
public Money {
Objects.requireNonNull(amount);
Objects.requireNonNull(currency);
if (amount.signum() < 0) {
throw new IllegalArgumentException("Amount cannot be negative");
}
}
// Business logic in value object
public Money add(Money other) {
if (!this.currency.equals(other.currency)) {
throw new IllegalArgumentException(
"Cannot add " + this.currency + " + " + other.currency
);
}
return new Money(this.amount.add(other.amount), this.currency);
}
public Money multiply(BigDecimal factor) {
if (factor.signum() < 0) {
throw new IllegalArgumentException("Multiplier cannot be negative");
}
return new Money(this.amount.multiply(factor), this.currency);
}
public boolean isGreaterThan(Money other) {
if (!this.currency.equals(other.currency)) {
throw new IllegalArgumentException("Different currencies, cannot compare");
}
return this.amount.compareTo(other.amount) > 0;
}
}
Slug Value Object (with complex validation)
// Value Object: Slug for URL, immutable, validated
public record Slug(String value) {
public Slug {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Slug cannot be empty");
}
// Slug: lowercase, alphanumeric and dash, max 100 char
if (!value.matches("^[a-z0-9-]{1,100}$")) {
throw new IllegalArgumentException(
"Invalid slug: only lowercase, alphanumeric and dash (e.g., 'my-article-slug')"
);
}
if (value.startsWith("-") || value.endsWith("-")) {
throw new IllegalArgumentException("Slug cannot start or end with dash");
}
}
public static Slug fromTitle(String title) {
return new Slug(
title.toLowerCase()
.replaceAll("[^a-z0-9\\s-]", "")
.replaceAll("\\s+", "-")
.replaceAll("-+", "-")
.substring(0, Math.min(100, title.length()))
);
}
}
Business Logic in Domain
Principle: Logic in Domain, Not in Service
You often see code like this:
// ANTI-PATTERN: Business logic in service
@Service
public class UserService {
public void register(RegisterRequest req) {
// Email validation scattered here
if (!isEmailValid(req.email())) {
throw new InvalidEmail();
}
// Update scattered here
User user = new User();
user.setEmail(req.email());
userRepository.save(user);
}
private boolean isEmailValid(String email) {
// Duplicated in 3 other services
return email.contains("@");
}
}
Problem: Logic is scattered, duplicated, hard to test in isolation.
Clean Domain Approach:
// Domain layer: Logic in domain
public record User(...) {
public Email {
// Validation in value object, not in service
// Reusable everywhere
}
}
// Application layer: Service calls domain
@Service
public class RegisterUserUseCase {
public User execute(RegisterRequest req) {
// Construct value object (validation happens here)
Email email = new Email(req.email()); // Throws if invalid
// Create user domain
User newUser = User.register(email, req.hashedPassword(), req.name());
// Save (via port)
return userRepository.save(newUser);
}
}
Aggregate Roots and Bounded Context
Aggregate Root: User is the Entry Point
If User has 0..N Article, User is the aggregate root. Don't access Article directly from repository; access it via User.
// Aggregate: User + List<Article>
public record UserAggregate(
User user,
List<Article> articles // Entities under User control
) {
// Business logic that operates on entire aggregate
public UserAggregate publishArticle(String title, String body) {
// Create article in context of User
Article newArticle = Article.create(
ArticleId.generate(),
this.user.id(),
title,
body,
ZonedDateTime.now(ZoneId.of("UTC"))
);
// Add to aggregate
List<Article> updatedArticles = new ArrayList<>(this.articles);
updatedArticles.add(newArticle);
return new UserAggregate(this.user, Collections.unmodifiableList(updatedArticles));
}
public int articleCount() {
return articles.size();
}
}
Domain Events: Communication Between Bounded Contexts
Why Domain Events
When a user registers, you want to send welcome email, create audit record, update statistics. Domain event enables this without coupling domain to EmailSender, AuditLog, etc.
// Domain Event: Significant fact
public record UserRegisteredEvent(
UserId userId,
Email email,
ZonedDateTime occurredAt
) implements DomainEvent {
public UserRegisteredEvent(User user) {
this(user.id(), user.email(), ZonedDateTime.now(ZoneId.of("UTC")));
}
}
// Entity publishes event
public record User(...) {
private List<DomainEvent> domainEvents = new ArrayList<>();
public static User register(Email email, String hashedPassword, UserName name) {
User user = new User(
UserId.generate(),
email,
hashedPassword,
name,
PremiumStatus.FREE,
ZonedDateTime.now(ZoneId.of("UTC")),
null
);
// Note: in immutable record, you can't modify the list
// Solution: return record with user + events
return user;
}
// Alternative: return record with user + events
public record RegisterResult(User user, List<DomainEvent> events) { }
}
// Application layer: Listen to events
@Service
@Transactional
public class RegisterUserUseCase {
public void execute(RegisterRequest req) {
Email email = new Email(req.email());
User newUser = User.register(email, req.hashedPassword(), req.name());
userRepository.save(newUser);
// Publish event (event bus, Kafka, or simple observer pattern)
eventPublisher.publish(new UserRegisteredEvent(newUser));
}
}
// Event handler (in application layer)
@Service
public class SendWelcomeEmailOnUserRegistered {
private final EmailSender emailSender;
@EventListener
public void handle(UserRegisteredEvent event) {
emailSender.sendWelcome(event.email());
}
}
Ports in Domain Layer
Port: Contract for Interacting with Infrastructure
A port is an interface in the domain that infrastructure implements. It allows domain to remain agnostic to implementation details.
// Domain Layer: Port (interface, no Spring annotations)
public interface UserRepository {
Optional<User> findById(UserId id);
Optional<User> findByEmail(Email email);
User save(User user); // Return saved user (for potential update)
void delete(UserId id);
List<User> findAllPremium();
}
// Domain Layer: Port for email
public interface EmailSender {
void sendWelcome(Email email);
void sendPasswordReset(Email email, String resetLink);
}
Anti-pattern: JPA Entity in Domain
Why Not
Seeing @Entity in domain layer means domain depends on Spring Data JPA. If tomorrow you change persistence library, you must rewrite domain. Wrong.
// ANTI-PATTERN: @Entity in domain
@Entity // Domain shouldn't know about JPA
@Table(name = "users")
public class User {
@Id @GeneratedValue
private UUID id;
@Column(unique = true)
private String email; // Naked string, not Email value object
// Only getter/setter, zero logic
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
// PATTERN: Pure domain + separate JPA Entity
// Domain Layer
public record User(UserId id, Email email, ...) { }
// Infrastructure Layer
@Entity
@Table(name = "users")
public class UserJpaEntity {
@Id
private String id;
@Column(unique = true)
private String emailValue; // String, not domain Entity
}
// Infrastructure Layer: Adapter that converts
@Repository
public class UserJpaAdapter implements UserRepository {
private final UserJpaRepository jpaRepository;
@Override
public Optional<User> findByEmail(Email email) {
return jpaRepository.findByEmailValue(email.value())
.map(this::mapToDomain);
}
private User mapToDomain(UserJpaEntity jpaEntity) {
return new User(
new UserId(UUID.fromString(jpaEntity.getId())),
new Email(jpaEntity.getEmailValue()),
...
);
}
}
Practical Modeling: Blog Domain
Scenario: Blog with Articles and Authors
// Value Objects
public record ArticleId(UUID value) { }
public record ArticleSlug(String value) {
public ArticleSlug {
if (!value.matches("^[a-z0-9-]{1,100}$")) {
throw new IllegalArgumentException("Invalid slug: " + value);
}
}
}
// Entity
public record Article(
ArticleId id,
ArticleSlug slug,
String title,
String body,
UserId authorId,
PublishStatus status,
ZonedDateTime createdAt,
ZonedDateTime publishedAt // nullable until publication
) {
public Article {
Objects.requireNonNull(id);
Objects.requireNonNull(slug);
Objects.requireNonNull(title);
Objects.requireNonNull(body);
Objects.requireNonNull(authorId);
Objects.requireNonNull(status);
Objects.requireNonNull(createdAt);
}
public boolean isPublished() {
return status == PublishStatus.PUBLISHED && publishedAt != null;
}
public Article publish() {
if (this.status == PublishStatus.PUBLISHED) {
throw new IllegalArgumentException("Article already published");
}
return new Article(
this.id, this.slug, this.title, this.body, this.authorId,
PublishStatus.PUBLISHED, // Update status
this.createdAt,
ZonedDateTime.now(ZoneId.of("UTC")) // Set publishedAt
);
}
public static Article create(String title, String body, UserId authorId) {
return new Article(
new ArticleId(UUID.randomUUID()),
ArticleSlug.fromTitle(title),
title,
body,
authorId,
PublishStatus.DRAFT,
ZonedDateTime.now(ZoneId.of("UTC")),
null
);
}
}
public enum PublishStatus {
DRAFT, PUBLISHED, ARCHIVED;
}
Domain Entity Test (1ms, no Spring)
// Test: domain entity, zero Spring context
public class UserTest {
@Test
public void testCreateUser() {
User user = User.register(
new Email("test@example.com"),
"$2a$12$...", // BCrypt hash
new UserName("John", "Doe")
);
assertNotNull(user.id());
assertEquals("test@example.com", user.email().value());
assertEquals(PremiumStatus.FREE, user.premiumStatus());
}
@Test
public void testPasswordValidation() {
User user = new User(
new UserId(UUID.randomUUID()),
new Email("test@example.com"),
BCrypt.hashpw("password123", BCrypt.gensalt()),
new UserName("John", "Doe"),
PremiumStatus.FREE,
ZonedDateTime.now(),
null
);
assertTrue(user.isPasswordValid("password123"));
assertFalse(user.isPasswordValid("wrongpassword"));
}
@Test
public void testEmailValidation() {
assertThrows(IllegalArgumentException.class,
() -> new Email("invalid-email"));
assertThrows(IllegalArgumentException.class,
() -> new Email(""));
Email valid = new Email("test@example.com");
assertEquals("test@example.com", valid.value());
}
@Test
public void testUpgradeUserToPremiun() {
User freeUser = User.register(
new Email("test@example.com"),
"hash",
new UserName("John", "Doe")
);
User premiumUser = freeUser.upgradeToPremiun();
assertEquals(PremiumStatus.FREE, freeUser.premiumStatus()); // Original unchanged
assertEquals(PremiumStatus.ACTIVE, premiumUser.premiumStatus()); // New
}
}
FAQ - Domain Layer
Q1. Should I use Java records for all entities?
Answer: Yes, especially in Java 21+. Records force you to think in terms of immutability, which is exactly what you want in domain layer. Syntax is concise, reduces boilerplate, and compiler generates equals/hashCode/toString. Only downside: if you really need mutability (rare in domain layer), use a classic class, but document it well.
Q2. What if the domain is really simple? Can I skip value objects?
Answer: Depends. If Email is used in one place and has no validation, String is fine. But as soon as you use it in 2+ places or have rules (validation, format), create the value object. Cost is minimal (3-5 lines), benefit is huge: logic centralization, reusability, error protection.
Q3. How do I manage relationships between entities in domain? Is User.articles OK?
Answer: Depends on cohesion. If Article is always accessed via User (aggregate root), then User can contain articles. If Article is independent, then no — access via separate repository. In the blog example above, Article could be independent (accessed from ArticleRepository) or under User (accessed only from UserRepository.findUserWithArticles). Decide based on business logic.
Q4. Immutability in records: how do I handle side effects (e.g., incrementing counter)?
Answer: You don't have side effects; return new entity. E.g. User upgradedUser = user.upgradeToPremiun(). If you need to maintain local state (e.g., list of domain events), use a classic class with methods that modify the list, but keep the entity itself immutable. Or use the pattern "RegisterResult" that returns entity + events together.
Q5. How do I test a domain service that depends on a port?
Answer: Mock the port. In test, create a mock UserRepository, inject it in the service, verify behavior. Example: when(repo.findByEmail(email)).thenReturn(Optional.empty()). This is a "logic in isolation" test, which is the point of the domain layer.
Conclusion: Domain Layer is the Foundation
The domain layer isolates business logic in a pure, framework-agnostic, testable "fortress". Build:
- Entities with Java records: Immutable, concise, full of business logic.
- Value objects with validation: Email, Money, Slug protect data at constructor.
- Ports as contracts: Repository, EmailSender, etc. remain abstract in domain.
- Domain events for communication: UserRegisteredEvent, ArticlePublishedEvent decouple bounded contexts.
- Zero framework: Spring, JPA, HTTP stay out of domain.
In Federico's backend (1521 Java files), the domain layer was isolated from day 1. Result: when business logic changes, update domain. When infrastructure technology changes (PostgreSQL to MongoDB, SMTP to SendGrid), update only infrastructure adapters. Domain stays stable.
External Resources
- Domain-Driven Design - Wikipedia
- Java Records - Official Documentation
- Hexagonal Architecture (Ports & Adapters) - Martin Fowler
- Clean Architecture - Wikipedia
- Implementing Domain-Driven Design - Vaughn Vernon
Next Step: Infrastructure Layer
Now that you have pure domain, the next step is implementing the infrastructure layer: JPA adapter, Redis cache, SMTP email sender. Read "JPA and Flyway: Persistence in Infrastructure Layer" to learn how to keep domain isolated.

Commenti
Caricamento commenti...
Sign in to comment