Domain-Driven Design
Use when evolving aggregate invariants, value objects or domain events in an existing DDD-style Spring Boot 3 application, or when DDD is explicitly requested. Preserve existing API identifiers and architecture when changing domain behavior.
View SKILL.mdAggregate Rules
- One repository per aggregate root
- External code only accesses aggregate through root — never child entities directly
- Prefer references by ID across aggregate boundaries; preserve deliberate mappings.
- Choose boundaries from invariants that must commit atomically and expected contention, not a fixed number of child entities. Splitting requires an explicit consistency plan.
The snippets are illustrative and require the application's domain types and imports. Keep existing public identifiers and persistence mappings unless the task includes a migration.
// ✅ Aggregate root controls all access to children
order.addItem(productId, quantity); // through root
order.removeItem(itemId); // through root
// ❌ Direct child access from outside
order.getItems().add(new OrderItem(...)); // bypasses invariants
Value Objects
Immutable, no identity, equality by value:
public record Money(BigDecimal amount, Currency currency) {
public Money {
if (amount.compareTo(BigDecimal.ZERO) < 0)
throw new IllegalArgumentException("Amount cannot be negative");
Objects.requireNonNull(currency);
}
public Money add(Money other) {
if (!currency.equals(other.currency))
throw new CurrencyMismatchException(currency, other.currency);
return new Money(amount.add(other.amount), currency);
}
public static Money of(String amount, String currency) {
return new Money(new BigDecimal(amount), Currency.getInstance(currency));
}
}
public record EmailAddress(String value) {
public EmailAddress {
if (!value.matches("^[\\w.-]+@[\\w.-]+\\.[a-z]{2,}$"))
throw new InvalidEmailException(value);
}
}
Domain Events
// Event — immutable record
public record OrderPlaced(OrderId orderId, CustomerId customerId, Money total, Instant occurredAt) {
public static OrderPlaced of(Order order) {
return new OrderPlaced(order.getId(), order.getCustomerId(), order.getTotal(), Instant.now());
}
}
// Collect events in aggregate, publish after save
@Entity
public class Order {
@Transient
private final List<Object> domainEvents = new ArrayList<>();
public void place() {
this.status = OrderStatus.PLACED;
domainEvents.add(OrderPlaced.of(this));
}
public List<Object> pullDomainEvents() {
var events = List.copyOf(domainEvents);
domainEvents.clear();
return events;
}
}
// Publish inside the transaction; save() is not commit.
@Service
@RequiredArgsConstructor
public class OrderApplicationService {
private final OrderRepository orderRepository;
private final ApplicationEventPublisher eventPublisher;
@Transactional
public Order placeOrder(PlaceOrderCommand command) {
Order order = orderRepository.findById(command.orderId()).orElseThrow();
order.place();
Order saved = orderRepository.save(order);
saved.pullDomainEvents().forEach(eventPublisher::publishEvent); // commit-bound listener below
return saved;
}
}
// Listen to events — bind to commit, not just publish.
// @EventListener fires synchronously inside the TX; if the TX later rolls back you've
// already sent the email. AFTER_COMMIT avoids rollback delivery but is best effort.
@Component
@RequiredArgsConstructor
public class OrderPlacedHandler {
private final EmailService emailService;
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void onOrderPlaced(OrderPlaced event) {
emailService.sendOrderConfirmation(event.customerId(), event.orderId());
}
}
Let Spring Data publish for you. Instead of calling
pullDomainEvents()by hand, expose a@DomainEventsmethod (returns the collected events) and an@AfterDomainEventPublicationmethod (clears them) on the aggregate root. Spring Data's repository drains and publishes them automatically on everysave()— no manual wiring in the service.
Neither publication mechanism guarantees durable delivery. For required external effects,
persist an outbox entry with the aggregate change or use a persistent publication registry,
with idempotent consumers and retry/recovery. @Async changes execution, not durability.
Post-commit database writes need a new transaction because the original resources may still
be bound after completion. See transaction boundaries,
messaging and Modulith.
Specifications (complex queries)
public class OrderSpecifications {
public static Specification<Order> byStatus(OrderStatus status) {
return (root, query, cb) -> cb.equal(root.get("status"), status);
}
public static Specification<Order> byCustomer(UUID customerId) {
return (root, query, cb) -> cb.equal(root.get("customerId"), customerId);
}
public static Specification<Order> placedAfter(Instant date) {
return (root, query, cb) -> cb.greaterThan(root.get("placedAt"), date);
}
}
// Compose
Specification<Order> spec = OrderSpecifications.byStatus(PLACED)
.and(OrderSpecifications.byCustomer(customerId))
.and(OrderSpecifications.placedAfter(lastWeek));
orderRepository.findAll(spec, pageable);
Anti-Corruption Layer (ACL)
- When integrating with external systems or legacy code, don't let their models leak into your domain
- Create an ACL — a translation layer that converts external data to your domain language
- ACL lives in infrastructure layer, not domain
// ✅ GOOD — ACL translates external payment API to domain concepts
@Component
@RequiredArgsConstructor
public class PaymentGatewayAdapter implements PaymentPort {
private final ExternalPaymentClient client; // third-party SDK
@Override
public PaymentConfirmation charge(OrderId orderId, Money amount) {
// Translate domain → external
PaymentApiRequest apiRequest = new PaymentApiRequest(
orderId.value().toString(),
amount.amount(), // illustrative provider accepts BigDecimal
amount.currency().getCurrencyCode());
// Call external system
PaymentApiResponse apiResponse = client.charge(apiRequest);
// Translate external → domain
return new PaymentConfirmation(
PaymentId.of(apiResponse.getTransactionId()),
apiResponse.isSuccessful() ? PaymentStatus.CONFIRMED : PaymentStatus.DECLINED);
}
}
Use the provider's exact monetary representation. For integer minor units, convert with the currency's fraction digits and exact arithmetic; do not silently round or convert money to binary floating point.
Verification
Test aggregate invariants, rollback preventing external notification, and recovery from a crash after commit for durable publication. Verify that existing API IDs and database relationships remain compatible with the requested change.
Gotchas
- Agent creates anemic models with only getters/setters — put behavior on domain objects
- Agent replaces existing Long/UUID API IDs with value objects - preserve the public contract; map internal types explicitly.
- Agent puts domain logic in services — services should orchestrate, not decide
- Agent accesses child entities directly from outside — always go through aggregate root
- Agent confuses save with commit - publish in the transaction and select listener/durable delivery semantics deliberately.
- Agent splits an aggregate at an arbitrary child count - derive boundaries from business invariants.
- Agent lets external API models into domain — use an Anti-Corruption Layer to translate
Official sources
Examples & templates
bad-aggregate.javaexamples
// ❌ BAD — anemic model, no invariant enforcement, no typed IDs, no events
@Entity
@Data // generates public setters — anyone can mutate state
@NoArgsConstructor // public no-arg constructor allows invalid objects
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; // Long ID — not a typed value object
private Long customerId; // Long — should be CustomerId value object
private String customerEmail; // raw String — should be EmailAddress value object
@Enumerated(EnumType.ORDINAL) // ORDINAL breaks if enum is reordered
private OrderStatus status;
private BigDecimal total; // raw BigDecimal — should be Money value object
@OneToMany(mappedBy = "order") // missing cascade, orphanRemoval
private List<OrderItem> items; // not initialized — NPE risk
// No behavior methods — all logic will live in service:
// - No addItem() method
// - No place() method
// - No state transition validation
// - No domain events
// - Total is set manually from outside, not calculated
// External code does:
// order.getItems().add(new OrderItem(...)); // bypasses aggregate boundary
// order.setStatus(OrderStatus.PLACED); // no invariant check
// order.setTotal(calculateTotal(items)); // logic outside domain
}good-aggregate.javaexamples
// ✅ GOOD — rich domain model, typed IDs, behavior methods, domain events, no public setters
public class Order {
private final OrderId id;
private final CustomerId customerId;
private final EmailAddress customerEmail;
private final Currency currency;
private OrderStatus status;
private Money total;
private final List<OrderItem> items = new ArrayList<>();
@Transient
private final List<Object> domainEvents = new ArrayList<>();
private Order(OrderId id, CustomerId customerId, EmailAddress customerEmail, Currency currency) {
this.id = Objects.requireNonNull(id);
this.customerId = Objects.requireNonNull(customerId);
this.customerEmail = Objects.requireNonNull(customerEmail);
this.currency = Objects.requireNonNull(currency);
this.status = OrderStatus.DRAFT;
this.total = Money.zero(currency);
}
// Static factory — enforces valid initial state
public static Order create(CustomerId customerId, EmailAddress email, Currency currency) {
return new Order(OrderId.generate(), customerId, email, currency);
}
// Behavior methods enforce invariants
public void addItem(ProductId productId, String name, int quantity, Money unitPrice) {
if (status != OrderStatus.DRAFT)
throw new OrderNotModifiableException(id);
if (quantity <= 0)
throw new InvalidQuantityException(quantity);
if (!unitPrice.currency().equals(currency))
throw new CurrencyMismatchException(currency, unitPrice.currency());
items.add(new OrderItem(productId, name, quantity, unitPrice));
recalculateTotal();
}
public void place() {
if (items.isEmpty())
throw new EmptyOrderException(id);
if (status != OrderStatus.DRAFT)
throw new IllegalOrderStateTransitionException(status, OrderStatus.PLACED);
this.status = OrderStatus.PLACED;
domainEvents.add(OrderPlaced.of(this));
}
public void cancel(String reason) {
if (status == OrderStatus.SHIPPED || status == OrderStatus.DELIVERED)
throw new IllegalOrderStateTransitionException(status, OrderStatus.CANCELLED);
this.status = OrderStatus.CANCELLED;
domainEvents.add(new OrderCancelled(id, customerId, reason, Instant.now()));
}
public List<Object> pullDomainEvents() {
var events = List.copyOf(domainEvents);
domainEvents.clear();
return events;
}
private void recalculateTotal() {
this.total = items.stream()
.map(OrderItem::lineTotal)
.reduce(Money.zero(currency), Money::add);
}
// No public setters — state changes only through behavior methods
public OrderId getId() { return id; }
public CustomerId getCustomerId() { return customerId; }
public OrderStatus getStatus() { return status; }
public Money getTotal() { return total; }
public List<OrderItem> getItems() { return Collections.unmodifiableList(items); }
}
// Typed ID — value object
public record OrderId(UUID value) {
public static OrderId generate() { return new OrderId(UUID.randomUUID()); }
public static OrderId of(UUID value) { return new OrderId(Objects.requireNonNull(value)); }
}DomainEvent.javatemplates
package com.example.common.domain;
import java.time.Instant;
import java.util.UUID;
/**
* Base interface for all domain events.
* Events are immutable facts about something that happened in the domain.
*/
public interface DomainEvent {
UUID eventId();
Instant occurredAt();
}
// --- Concrete domain events as records ---
package com.example.order.domain.event;
import com.example.common.domain.DomainEvent;
import com.example.order.domain.model.CustomerId;
import com.example.order.domain.model.Money;
import com.example.order.domain.model.OrderId;
import java.time.Instant;
import java.util.UUID;
public record OrderPlaced(
UUID eventId,
Instant occurredAt,
OrderId orderId,
CustomerId customerId,
Money total
) implements DomainEvent {
public static OrderPlaced of(Order order) {
return new OrderPlaced(
UUID.randomUUID(),
Instant.now(),
order.getId(),
order.getCustomerId(),
order.getTotal()
);
}
}
public record OrderCancelled(
UUID eventId,
Instant occurredAt,
OrderId orderId,
CustomerId customerId,
String reason
) implements DomainEvent {
public OrderCancelled(OrderId orderId, CustomerId customerId, String reason, Instant occurredAt) {
this(UUID.randomUUID(), occurredAt, orderId, customerId, reason);
}
}Money.javatemplates
package com.example.common.domain;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Currency;
import java.util.Objects;
/**
* Value object representing monetary amount with currency.
* Immutable — all operations return new instances.
*/
public record Money(BigDecimal amount, Currency currency) {
// No shared ZERO constant: a USD zero silently breaks every non-USD aggregate
// the first time it is used as a starting total or a reduce() identity.
public static Money zero(Currency currency) {
return new Money(BigDecimal.ZERO, currency);
}
public Money {
Objects.requireNonNull(amount, "Amount must not be null");
Objects.requireNonNull(currency, "Currency must not be null");
if (amount.compareTo(BigDecimal.ZERO) < 0)
throw new IllegalArgumentException("Amount cannot be negative: " + amount);
// Scale to the currency (JPY 0, EUR 2, BHD 3) and refuse to round: losing
// precision in a money value must fail loudly, never happen silently.
amount = amount.setScale(currency.getDefaultFractionDigits(), RoundingMode.UNNECESSARY);
}
public static Money of(BigDecimal amount, Currency currency) {
return new Money(amount, currency);
}
public static Money of(String amount, String currencyCode) {
return new Money(new BigDecimal(amount), Currency.getInstance(currencyCode));
}
public static Money usd(String amount) {
return of(amount, "USD");
}
public Money add(Money other) {
assertSameCurrency(other);
return new Money(amount.add(other.amount), currency);
}
public Money subtract(Money other) {
assertSameCurrency(other);
BigDecimal result = amount.subtract(other.amount);
if (result.compareTo(BigDecimal.ZERO) < 0)
throw new IllegalArgumentException("Result would be negative");
return new Money(result, currency);
}
public Money multiply(int quantity) {
return new Money(amount.multiply(BigDecimal.valueOf(quantity)), currency);
}
public boolean isGreaterThan(Money other) {
assertSameCurrency(other);
return amount.compareTo(other.amount) > 0;
}
private void assertSameCurrency(Money other) {
if (!currency.equals(other.currency))
throw new IllegalArgumentException(
"Currency mismatch: %s vs %s".formatted(currency, other.currency));
}
@Override
public String toString() {
return "%s %s".formatted(currency.getCurrencyCode(), amount);
}
}Verification scope
- Compiled sources
- No
- Runtime checks
- No
Coverage describes checked-in fixtures, not a guarantee for every snippet or project.
Coverage matrix & agent evidenceADD TO YOUR AGENTInstall Boot 3 skills
Install Boot 3 skills
claude plugin marketplace add rrezartprebreza/spring-boot-skills
claude plugin install spring-boot-3-skills@spring-boot-skillscodex plugin marketplace add rrezartprebreza/spring-boot-skills
codex plugin add spring-boot-3-skills@spring-boot-skills