SuperAPI AI Directory

ddd-architecture-layered

Coding & development

View repository

Updated 10-15 21:48

About this skill

DDD Layered Architecture — Layered Architecture Implementation Guide

DDD Layered Architecture is the simplest introductory architecture in the DDD ecosystem. It refactors the traditional three layers (Controller/Service/DAO) into four layers (Interface/Application/Domain/Infrastructure), making the domain layer the core of the system through dependency inversion.

Audience — Target Users

User Type Characteristics Recommended Entry Point
DDD Beginner Understands MVC three layers, wants to get started with DDD Read Core Principles first → look at 06 Monolith Simple Example → follow Implementation Phases
Architect Responsible for project architecture selection and technical planning Read When to Use boundaries first → select based on the 06-12 scale spectrum → look at the Evolution path
Senior Developer Has three-layer development experience, needs to implement layering Go directly to Directory Structure + Writing Rules → use the 07/08 examples to start the project
Technical Lead Evaluates the feasibility and cost of introducing DDD to the team Read When to Use + scenario boundaries first → evaluate Implementation Phases time → refer to 09-12 microservice planning

Workflow

Step 1: awesome (入门)              →  了解 DDD 概念
Step 2: selector (架构选型)         →  确认分层架构适合
Step 3: layered (分层架构) ★         ← 你在这里
Step 4: domain-designer (领域设计)  →  设计领域模型
Step 5: code-reviewer (审查)        →  分层合规检查

When to Use — Scenario Boundaries

✅ Applicable Scenarios

# Scenario Description
1 Team < 10 people, DDD just getting started Low learning curve, layered architecture is the simplest entry point
2 Medium-complexity business with a clear domain model Clear aggregate roots, rich benefits from a rich domain model
3 Existing three-layer project evolving gradually Three-layer→four-layer gradual migration, without overturning the original architecture
4 Spring Boot/MyBatis technology stack Mainstream domestic technology stack, examples can be reused directly

⚠️ Conditional (Usable After Careful Evaluation)

# Scenario Condition
1 Team of 10-20 people Need to first evaluate whether physical module isolation is needed → see 08 Multi-Module Solution
2 Complex business with multiple aggregate roots Need to confirm aggregate boundaries are clear → do Event Storming first, then implement layering
3 Already intends to split into microservices First implement a single service with layered architecture → then refer to the 09-12 microservice solutions for splitting
4 Non-Spring Boot technology stack DDD layering ideas are universal, but directory structure and code examples need to be adapted accordingly

❌ Not Applicable Scenarios

# Scenario Alternative
1 Pure CRUD with no business rules Directly use Spring Boot three layers + MyBatis-Plus to save cost
2 Multi-entry system (REST+CLI+MQ) Referring to Hexagonal Architecture is more appropriate
3 Need physical module isolation Use COLA architecture or microservice solutions (see 09-12 examples)
4 High-frequency infrastructure replacement When infrastructure changes frequently, Clean Architecture is recommended

Prerequisite: Have a stable domain expert + the team is willing to switch to a rich domain model.

Core Principles — 核心原理

Three Layers → Four Layers

三层架构:           DDD 四层:
Controller          Interface (用户接口层)
  ↓                   ↓
Service             Application (应用层) — 纯编排
  ↓                   ↓
DAO                 Domain (领域层) ★ — 核心业务
                      ↓
                    Infrastructure (基础设施层)

Four Core Principles

# Principle Description
1 Domain Zero Dependency Does not import Spring/JPA/MyBatis
2 Dependency Inversion Infra implements interfaces defined by Domain
3 Application Thin Layer Only orchestration, no business if/else
4 Interface Protocol Conversion Only DTO conversion, no business logic

Directory Structure

{project}/
├── {project}-interface/              # 用户接口层
│   ├── controller/                   # REST 控制器
│   ├── dto/                          # 请求/响应 DTO
│   │   ├── request/
│   │   └── response/
│   ├── converter/                    # DTO ↔ Command 转换
│   └── advice/                       # 全局异常处理
├── {project}-application/            # 应用层
│   ├── service/                      # 应用服务(纯编排)
│   ├── command/                      # 命令对象(写)
│   ├── query/                        # 查询对象(读)
│   ├── assembler/                    # DO ↔ DTO 组装
│   └── event/                        # 事件处理
├── {project}-domain/                 # 领域层 ★(零依赖)
│   ├── {aggregate}/                  # 按聚合分包
│   │   ├── entity/                   # 实体+聚合根(充血)
│   │   ├── valueobject/              # 值对象(不可变)
│   │   ├── service/                  # 领域服务
│   │   ├── repository/               # 仓储接口(只定义)
│   │   └── event/                    # 领域事件
│   ├── factory/                      # 领域工厂
│   └── shared/                       # 共享值对象
└── {project}-infrastructure/         # 基础设施层
    ├── repository/                   # 仓储实现
    ├── persistence/                  # PO 实体+映射
    ├── messaging/                    # 消息队列
    ├── external/                     # 外部服务
    └── config/                       # 配置

Writing Rules — 开发规范

Dependency Direction:Interface → Application → Domain ← Infrastructure

Layer Can Depend On Cannot Depend On
Interface Application Domain、Infrastructure
Application Domain Interface、Infrastructure
Domain JDK native types All other layers + frameworks
Infrastructure Domain Interface、Application

Code Naming:

  • Aggregate Root:Order(business name, not OrderEntity)
  • Value Object:Money、Email(immutable, no setter)
  • Repository Interface:OrderRepository(in Domain)
  • Repository Implementation:JpaOrderRepository(in Infra)
  • Domain Event:OrderPlaced(past tense)

Prohibitions:

  • Prohibited: business if/else judgments in Controller
  • Prohibited: Application Service writing SQL
  • Prohibited: Domain layer importing Spring or JPA annotations
  • Prohibited: direct object references across aggregates (use ID references)

Implementation Phases

Phase 1: 识别聚合(1-2天)
  → 事件风暴 → 聚合根 → 不变式 → 通用语言表

Phase 2: 搭建分层骨架(1天)
  → 多模块 pom.xml → 基类(Entity/VO/AggregateRoot)

Phase 3: 实现领域层(2-5天)
  → 充血模型 → Repository 接口 → 领域服务 → 领域事件

Phase 4: 实现基础设施层(2-3天)
  → Repository 实现 → PO↔DO 映射 → DB 配置

Phase 5: 实现应用层(1-2天)
  → AppService 编排 → Command/Query → 事务管理

Phase 6: 实现接口层(1-2天)
  → Controller → DTO → 参数校验 → 异常处理

Phase 7: 审查验证(0.5天)
  → ddd-code-reviewer → ArchUnit → Domain 测试 ≥ 80%

Evolution

Phase 1: 传统三层       ← 当前状态
Phase 2: 四层基础       ← 抽取 Domain + Infra
Phase 3: 充血模型       ← 实体含业务方法
Phase 4: 领域事件+CQRS  ← L1 模型分离
Phase 5: 升级架构       ← 根据需要选 Hexagonal/Clean/COLA

Gotchas

See for 15 common pitfalls references/09-gotchas.md。

FAQ

See for 15 common issues references/10-faq.md。

Keywords

layered architecture, DDD four layers, traditional layering, three layers to four layers, DDD layering, layered architecture, DDD layered, three tier to DDD four layer, dependency inversion, rich model, anemic model, repository pattern, Repository pattern, Spring Boot DDD, MyBatis DDD, DDD directory structure, ArchUnit layering check, dependency direction verification

References

File Content
references/01-domain-layer.md Domain layer in detail: entities, value objects, aggregates, domain services
references/02-application-layer.md Application layer in detail: AppService, Command/Query, transactions
references/03-interface-layer.md Interface layer in detail: Controller, DTO, exception handling
references/04-infrastructure-layer.md Infrastructure layer in detail: Repository implementation, PO mapping
references/05-dependency-rules.md Dependency direction rules and inter-layer communication conventions
references/06-migration-guide.md Three layers→four layers progressive migration guide
references/07-archunit-config.md ArchUnit automated verification configuration
references/08-cqrs-integration.md CQRS lightweight integration (L1 model separation)
references/09-gotchas.md 15 common pitfalls
references/10-faq.md 15 common issues

Examples

File Content
examples/spring-boot-order-example.md Complete Spring Boot order system example
examples/ddd4j-springboot-practice.md DDD4J Spring Boot in practice (Nova Coffee)
examples/partme-91-code-example.md Complete code for online leave request system
examples/ddd4j-spring-boot-guide.md Spring Boot DDD layering practical guide
examples/05-archunit-layered-config.md ArchUnit layering verification configuration
examples/06-monolith-simple.md Monolith simple project: single-module four-layer package split
examples/07-monolith-complex.md Monolith complex project: multiple aggregate roots + cross-aggregate orchestration
examples/08-monolith-multi-module.md Monolith multi-module: four-layer Maven module isolation
examples/09-microservice-simple.md Microservice simple: one DDD layered monolith per service
examples/10-microservice-complex.md Microservice complex: event-driven + Saga orchestration
examples/11-microservice-multi-module.md Microservice multi-module: four-layer submodule per service
examples/12-microservice-complex-multi.md Microservice complex multi-module: Shared Kernel + CQRS

Output

When using this Skill, the following outputs are provided:

  1. Project skeleton: Complete layered directory structure (multi-module or single-module)
  2. Base class templates:Entity/AggregateRoot/ValueObject/DomainEvent
  3. Dependency configuration: Maven/Gradle (including ArchUnit, Spring Boot, JPA)
  4. Complete Demo: An aggregate end-to-end implementation
  5. ArchUnit configuration: Automated verification of dependency direction
  6. Evolution roadmap: Three-layer → four-layer → optional architecture upgrade
  7. Migration guide: Migration steps for existing three-layer projects

Security & Stability

  • The code templates are teaching examples; please replace placeholders with environment configurations
  • ArchUnit rules enforce layered boundaries; it is recommended to integrate them into the CI pipeline
  • The DDD four-layer structure isolates domain logic from infrastructure, reducing the attack surface
  • This Skill does not include executable scripts; all operations are code generation and review
  • This Skill is a pure documentation-based Skill: it does not collect, process, or store any user data; it does not access the network or external services; and it does not use any third-party scripts.