SuperAPI AI Directory

ddd-architecture-cola

Deployment & operations

View repository

Updated 10-15 21:48

About this skill

DDD Architecture — COLA v5 (Diamond Architecture)

COLA v5 is Alibaba's open-source DDD architecture framework, adopting aDiamond Architecture—Domain at the center, with Adapter and Infrastructure on either side. This Skill merges cola-creator (scaffold generation) and cola-validator (architecture validation), providing full-process capability from creation to continuous validation.

Workflow

输入 → 意图识别
  ├─ "创建 COLA 项目" → Creator 流程(5 步)
  │   Step 1: 确认项目名/包名/语言/Spring Boot 版本/CQRS 开关
  │   Step 2: 生成多模块 Maven/Gradle 骨架
  │   Step 3: 生成基类(AggregateRoot/Entity/VO/DomainEvent)
  │   Step 4: 生成 Demo 聚合代码(四层完整链路)
  │   Step 5: 生成 ArchUnit 测试 + check_cola.py 脚本
  └─ "检查架构合规" → Validator 流程(4 步)
      Step 1: 接收项目路径或代码片段
      Step 2: 执行 6 项合规检查
      Step 3: P0/P1/P2 权重扣分,输出评分报告
      Step 4: 输出违规清单 + 修复建议
完成后引导 → ddd-domain-designer / ddd-api-designer / ddd-code-reviewer

When to Use / Boundary

When to use (applicable scenarios)

  • Java + Spring Boot enterprise projects, MyBatis/JPA tech stack
  • Need a scaffold to automatically generate a multi-module COLA project
  • Need ArchUnit to automatically validate architecture compliance
  • Domestic Alibaba tech ecosystem (Dubbo/RocketMQ/Nacos)
  • Team of 5-50 people, medium-to-high business complexity

Inapplicable scenarios

  • Non-Java projects → not applicable, recommend ddd-architecture-clean / ddd-architecture-hexagonal
  • Non-Spring Boot → not applicable, COLA is strongly bound to the Spring ecosystem
  • Simple CRUD for a 2-3 person team → not applicable,ddd-architecture-layered is more lightweight
  • Already running Clean/Hexagonal Architecture normally → not applicable, no migration needed
  • Rapid prototyping/PoC stage → not applicable, architecture cost is too high

Core principles of the Diamond Architecture

          ┌──────────────┐
          │   Adapter    │  ← 适配层:HTTP/MQ/RPC 协议适配与 DTO 转换
          └──────┬───────┘
          ┌──────▼───────┐
          │   Application│  ← 应用层:用例编排、事务管理、CQRS 执行器
  ┌───────┴───────┬───────┴───────┐
  ▼               ▼               ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│  Domain  │ │  Domain  │ │  Domain  │  ← 领域层:业务规则 ★ 零框架依赖
│   ★      │ │   ★      │ │   ★      │
└──────────┘ └──────────┘ └──────────┘
  ▲               ▲               ▲
  └───────────────┴───────────────┘
                 │
          ┌──────▼───────┐
          │Infrastructure│  ← 基础设施层:DB/MQ/缓存/外部 API 实现
          └──────────────┘
Layer Module Responsibility Dependency
Adapter {p}-adapter REST/RPC/MQ protocol adaptation, DTO conversion, parameter validation → app, domain
Application {p}-app Command/Query executors, transaction orchestration, extension point routing → domain, infra
Domain {p}-domain Aggregate/E/VO, domain events, Repository/Gateway interfaces, Ability No dependencies
Infrastructure {p}-infrastructure Repository/Gateway implementations, PO↔DO conversion, configuration, components → domain

New features in v5: Extension Point (@ExtensionPoint + @Extension(bizId) multi-tenant differentiation), Ability (domain capability abstraction), componentized infrastructure (distributed lock/rate limiting/circuit breaking), strengthened CQRS (strict separation of command/query executors)

Generation capability: cola-creator

AI 交互确认 → 项目名/包名(com.example.order) / 语言(Java 17+/Kotlin) / Spring Boot(3.2+/3.1) / CQRS(否/L1/L2) / Demo(默认Order)
生成内容:
  ├── pom.xml/build.gradle(6 模块:start/adapter/app/domain/infrastructure/common)
  ├── COLA v5 标准目录结构 + 基类(AggregateRoot/Entity/VO/DomainEvent)
  ├── Demo 聚合(Order 四层完整示例)
  ├── DDD 中间件配置(DomainEventBus、ExtensionExecutor)
  ├── ArchUnit 测试 + check_cola.py 脚本
  └── .gitignore + README

Two approaches:mvn archetype:generate -DarchetypeGroupId=com.alibaba.cola -DarchetypeArtifactId=cola-archetype-web -DarchetypeVersion=5.0.0(quick) or manual multi-module (recommended for production, see references/02).

Validation capability: cola-validator

Check item Level Description Detection method
Dependency direction P0 Domain must not depend on Infrastructure/App/Adapter import parsing
Domain purity P0 Domain has no Spring/JPA/MyBatis/Hibernate imports import scanning
Layer responsibilities P0 Adapter has no SQL, App has no business if/else AST analysis
Package naming conventions P1 Naming according to COLA conventions Regex matching
Module circular dependencies P1 DFS detection of dependency graph Graph traversal
Aggregate design P1 Aggregate > 5 entities, cross-aggregate references, value object mutability AST analysis

Scoring model:评分 = 100 - 扣分(P0=10分/项,P1=5分/项,P2=2分/项)。≥90→A,70-89→B,50-69→C,<50→D。

Run:mvn test -Dtest=ArchitectureComplianceTest(ArchUnit Java tests) or python scripts/check_cola.py /path/to/project(Python lightweight validation).

Directory Structure (COLA v5 Multi-module)

{project}/
├── start/               — 启动模块:Application.java(@EnableCola), config/
├── adapter/             — 适配器层
│   ├── web/             — controller/dto/advice(GlobalExceptionHandler)
│   ├── rpc/             — Dubbo/gRPC provider/consumer/facade
│   ├── job/             — 定时任务调度
│   └── message/         — MQ consumer/producer
├── app/                 — 应用层
│   ├── executor/        — command/query/event/extension 执行器
│   ├── model/           — command/query/event/dto 对象
│   ├── eventhandler/    — 事件处理器
│   └── extension/       — 扩展点(point/biz/impl)
├── domain/ ★            — 领域层(零框架依赖)
│   ├── model/           — entity/vo/aggregate/event/enums
│   ├── service/         — 领域服务
│   ├── ability/         — 领域能力(v5 新概念)
│   ├── gateway/         — 防腐层接口
│   └── repository/      — 仓储接口
├── infrastructure/      — 基础设施层
│   ├── config/          — DB/缓存/MQ/RPC 配置
│   ├── persistence/     — repositoryimpl/mapper/dao/entity(PO)
│   ├── gatewayimpl/     — 网关实现
│   ├── external/        — 外部服务客户端
│   └── component/       — 分布式锁/限流/熔断/重试
└── common/              — 常量/异常/工具/注解/上下文

Implementation Steps

Phase 1 [1 day] Scaffolding → Phase 2 [2-3 days] Domain Modeling (with ddd-domain-designer) → Phase 3 [2-3 days] Infrastructure (Repository/Gateway/PO) → Phase 4 [1-2 days] Application + Adapter (Executor → Controller) → Phase 5 [0.5 day] Architecture Validation → Phase 6 [Continuous] CI/CD Automated Validation

Core Rules

Four Major Constraints (P0): ①Domain has zero framework dependencies (Spring/JPA/MyBatis forbidden) ②App layer has no business if/else ③Adapter has no SQL/business judgment ④No circular dependencies between modules

Dependency Direction:adapter → app → domain ← infrastructure(domain depends on no one)

Gotchas — Common Pitfalls (15)

  1. Placing Controller in Domain layer — Controller belongs in the Adapter layer. The presence of @RestController under Domain indicates the layering is completely wrong.
  2. App layer directly operating Mapper — must go through the Repository interface:orderRepository.save(order) rather than orderMapper.insert()。
  3. Module naming does not match COLA — must be {project}-adapter/app/domain/infrastructure, otherwise ArchUnit validation fails.
  4. Placing Command/Query in Domain layer — should be placed in app/model/command/ and app/model/query/。
  5. Archetype version mismatch — cola-archetype-web 5.0.0 requires Spring Boot 3.x; 2.x requires manual adaptation.
  6. Using JPA @Entity in Domain layer — persistence mapping should use PO classes in the Infrastructure layer.
  7. App layer throwing framework exceptions — should throw BizException, converted uniformly in the Adapter layer.
  8. Directly referencing objects across aggregates — aggregates should reference each other by ID, not directly Order.getCustomer()。
  9. Value objects with setters — ValueObject should be immutable (final + no setters), modifications return a new object.
  10. Missing domain events — key operations such as order creation/payment/cancellation must publish domain events.
  11. Business judgment in Adapter layer — Controller/Consumer should not contain any if-else.
  12. God Service anti-pattern — a Service over 500 lines should be split by aggregate.
  13. Extension point without default implementation — every ExtensionPoint needs a default @Extension。
  14. Missing @EnableCola — the startup class must add @EnableCola to enable extension points and the event bus.
  15. Mixing PO and DO — persistent objects and domain objects must be separated, converted with a Converter.

FAQ (15)

Q1: What is the relationship between COLA v5 and Clean Architecture? COLA v5 is an Alibaba-style implementation of Clean Architecture, adding package naming conventions, an extension point mechanism, CQRS reinforcement, and scaffolding.

Q2: Why not generate directly with cola-archetype? Archetype is fast but rigid; manual setup is better suited for production customization.

Q3: Does COLA support microservices? Yes. Each microservice is internally organized into COLA's four layers, and services communicate via RPC/MQ.

Q4: Is CQRS mandatory? No. For simple scenarios use app/service/ orchestration; for complex scenarios switch to a CQRS executor.

Q5: What is the difference between check_cola.py and ArchUnit? check_cola.py lightweight import scanning is suitable for CI, ArchUnit's powerful AST analysis requires a Java environment.

Q6: How should @Autowired be handled in the Domain layer? The Domain layer prohibits @Autowired; inject interfaces via method parameters or constructors.

Q7: How is delivery of domain events guaranteed? In the App layer, after the transaction commits EventBus.publish(), production works with the Transactional Outbox pattern.

Q8: What is the relationship between COLA and Spring Cloud? COLA is an architectural specification, Spring Cloud is infrastructure; they can be fully integrated and used together.

Q9: Should value objects be stored as JSON or split into columns? Simple value objects are split into columns, complex nested ones are stored as JSON + Converter type conversion.

Q10: What to do when an aggregate is too large? ≤ 5 entities, split by business operation frequency.

Q11: Where does the extension point bizId come from? Frontend request headers, logged-in member level, tenant ID routing.

Q12: Can it be deleted if there is no extension point requirement? Yes.app/extension/ and domain/ability/ need not be created.

Q13: What is in the common module? Constants, exception base classes, DTO base classes, contexts (UserContext/TenantContext), custom annotations.

Q14: What is the relationship between start and adapter? start is the startup entry point + global configuration, adapter handles protocol adaptation, start depends on adapter.

Q15: How to ensure sensitive configuration is not leaked? Externalized configuration + environment variables, hardcoded keys are prohibited, the Domain layer does not read or write configuration files.

Keywords

COLA COLA v5 菱形架构 diamond architecture cola-creator cola-validator ArchUnit CQRS Extension Point 扩展点 Ability 领域能力 Aggregate Root Entity Value Object Domain Event Repository Gateway 防腐层 DDD Spring Boot MyBatis @EnableCola CommandExecutor QueryExecutor

Project Scaffolding

ddd4j Boot is a Java reference implementation of the COLA v5 architecture, based on Spring Boot 3.5.x, integrating the ddd-4-java and cqrs-4-java lightweight libraries, fully implementing DDD, CQRS, and Event Sourcing patterns.

  • Project generation: Use scripts/init_project.py to automatically generate a COLA multi-module project structure, supporting three project types: single-module monolith, multi-module monolith, and microservices, covering required files such as pom.xml, package-info.java, .gitignore, and mvnw
  • Compliance validation: Use scripts/check_project.py to validate the project's DDD layering compliance, dependency direction correctness, and package naming conventions, outputting detailed violation reports and remediation suggestions
  • Scenario examples: Refer to examples/13-architecture-patterns.md(four architecture patterns),examples/14-single-module.md(single-module monolith),examples/15-multi-module.md(multi-module monolith),examples/16-microservices.md(microservices)
  • Detailed description: Refer to references/14-ddd4j-scaffold.md to learn about the complete project generation process, validation rules, layer dependencies, and package naming conventions

References

For detailed reference, see the references/ directory: 01-architecture-principles (architecture principles), 02-project-scaffold (scaffold), 03-domain-layer (domain layer), 04-app-layer (application layer), 05-adapter-layer (adapter layer), 06-infrastructure (infrastructure), 07-archunit-validation (ArchUnit validation), 08-cqrs-integration (CQRS integration)

Examples

For complete code, see the examples/ directory: 01-quickstart-order (complete Order aggregate implementation), 02-customer-crud (CRUD introduction), 03-extension-point (extension point mechanism), 04-cqrs-separation (CQRS separation), 05-archunit-config (ArchUnit validation CI/CD integration)

For project scale examples, see examples/ Directories: 06-monolith-simple (monolith simple project), 07-monolith-complex (monolith complex project), 08-monolith-multi-module (monolith multi-module project), 09-microservice-simple-monolith (microservice simple monolith project), 10-microservice-complex-monolith (microservice complex monolith project, based on ddd4j-gateway), 11-microservice-simple-multi-module (microservice simple multi-module project, based on ddd4j-rednote), 12-microservice-complex-multi-module (microservice complex multi-module project, based on ddd4j-pay)