Clean Architecture 在后端项目中的实践:从分层到依赖注入

By | 2026年12月4日

为什么你的后端项目需要 Clean Architecture?

很多团队在项目初期为了快速上线,往往采用「Controller 直接调 Repository」的简单分层。随着业务增长,代码逐渐变成「意大利面条」:业务逻辑散落在 Controller 和 Service 中,数据库访问代码与业务规则耦合,单元测试难以编写,更换框架或数据库的成本极高。

Clean Architecture(整洁架构)由 Robert C. Martin 提出,核心思想是依赖倒置:内层(领域层)不依赖外层(框架、数据库),外层依赖内层。这样业务逻辑独立于技术细节,可测试、可替换。

本文以一个用户注册场景为例,从零搭建一个符合 Clean Architecture 的 Go 后端项目(语言不是重点,思想通用)。你将学到:

  • 如何划分实体、用例、接口适配器、框架四层
  • 如何通过依赖注入解耦
  • 如何处理事务等横切关注点
  • 常见踩坑与最佳实践

项目结构总览

我们采用如下目录结构(以 Go 为例,其他语言可借鉴):


├── cmd
│   └── api
│       └── main.go          # 依赖注入入口
├── internal
│   ├── domain               # 领域层:实体和仓储接口
│   │   ├── user.go
│   │   └── repository.go
│   ├── usecase              # 用例层:业务逻辑
│   │   └── register_user.go
│   ├── adapter              # 接口适配器层
│   │   ├── handler          # HTTP 处理器
│   │   │   └── user_handler.go
│   │   └── repository       # 仓储实现
│   │       └── user_repository.go
│   └── infrastructure       # 基础设施层:数据库、日志等
│       └── database.go
└── go.mod

注意:依赖方向必须从外向内,内层不能 import 外层包。这是整洁架构的铁律。

第一步:定义领域实体和仓储接口

领域层是最内层,包含业务实体和仓储接口(端口)。实体应包含业务规则,而不是贫血模型。


// internal/domain/user.go
package domain

import (
    "errors"
    "regexp"
    "time"
)

type User struct {
    ID        string
    Email     string
    Password  string // 实际应存储哈希
    CreatedAt time.Time
}

// 业务规则:邮箱格式校验
func (u *User) Validate() error {
    if u.Email == "" {
        return errors.New("email cannot be empty")
    }
    if !regexp.MustCompile(`^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$`).MatchString(u.Email) {
        return errors.New("invalid email format")
    }
    if len(u.Password) < 8 {
        return errors.New("password must be at least 8 characters")
    }
    return nil
}

仓储接口定义在领域层,但实现放在外层。这样用例层只依赖接口,不关心具体数据库。


// internal/domain/repository.go
package domain

import "context"

type UserRepository interface {
    Save(ctx context.Context, user *User) error
    FindByEmail(ctx context.Context, email string) (*User, error)
    ExistsByEmail(ctx context.Context, email string) (bool, error)
}

第二步:实现用例层(业务逻辑)

用例层编排领域对象和仓储接口,完成一个完整的业务操作。它不应该包含任何框架代码(如 HTTP 状态码、SQL 语句)。


// internal/usecase/register_user.go
package usecase

import (
    "context"
    "errors"
    "time"

    "github.com/google/uuid"
    "yourproject/internal/domain"
)

type RegisterUserInput struct {
    Email    string
    Password string
}

type RegisterUserOutput struct {
    UserID string
}

type RegisterUserUsecase struct {
    userRepo domain.UserRepository
}

func NewRegisterUserUsecase(repo domain.UserRepository) *RegisterUserUsecase {
    return &RegisterUserUsecase{userRepo: repo}
}

func (uc *RegisterUserUsecase) Execute(ctx context.Context, input RegisterUserInput) (*RegisterUserOutput, error) {
    // 1. 检查邮箱是否已存在
    exists, err := uc.userRepo.ExistsByEmail(ctx, input.Email)
    if err != nil {
        return nil, err
    }
    if exists {
        return nil, errors.New("email already registered")
    }

    // 2. 创建用户实体并校验
    user := &domain.User{
        ID:        uuid.NewString(),
        Email:     input.Email,
        Password:  input.Password, // 实际应哈希
        CreatedAt: time.Now(),
    }
    if err := user.Validate(); err != nil {
        return nil, err
    }

    // 3. 持久化
    if err := uc.userRepo.Save(ctx, user); err != nil {
        return nil, err
    }

    return &RegisterUserOutput{UserID: user.ID}, nil
}

💡 最佳实践:用例层的方法应返回领域错误或自定义错误类型,而不是 HTTP 错误。这样不同适配器(HTTP、gRPC)可以自行映射错误。

第三步:实现仓储(适配器层)

仓储实现放在适配器层,它依赖数据库驱动,但只实现领域层定义的接口。


// internal/adapter/repository/user_repository.go
package repository

import (
    "context"
    "database/sql"

    "yourproject/internal/domain"
)

type userRepository struct {
    db *sql.DB
}

func NewUserRepository(db *sql.DB) domain.UserRepository {
    return &userRepository{db: db}
}

func (r *userRepository) Save(ctx context.Context, user *domain.User) error {
    _, err := r.db.ExecContext(ctx,
        "INSERT INTO users (id, email, password, created_at) VALUES (?, ?, ?, ?)",
        user.ID, user.Email, user.Password, user.CreatedAt)
    return err
}

func (r *userRepository) FindByEmail(ctx context.Context, email string) (*domain.User, error) {
    row := r.db.QueryRowContext(ctx, "SELECT id, email, password, created_at FROM users WHERE email = ?", email)
    var u domain.User
    if err := row.Scan(&u.ID, &u.Email, &u.Password, &u.CreatedAt); err != nil {
        if err == sql.ErrNoRows {
            return nil, nil
        }
        return nil, err
    }
    return &u, nil
}

func (r *userRepository) ExistsByEmail(ctx context.Context, email string) (bool, error) {
    var exists bool
    err := r.db.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM users WHERE email = ?)", email).Scan(&exists)
    return exists, err
}

第四步:HTTP 处理器(适配器层)

处理器负责解析请求、调用用例、返回响应。它不应该包含业务逻辑。


// internal/adapter/handler/user_handler.go
package handler

import (
    "encoding/json"
    "net/http"

    "yourproject/internal/usecase"
)

type UserHandler struct {
    registerUC *usecase.RegisterUserUsecase
}

func NewUserHandler(uc *usecase.RegisterUserUsecase) *UserHandler {
    return &UserHandler{registerUC: uc}
}

func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
    var req struct {
        Email    string `json:"email"`
        Password string `json:"password"`
    }
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        http.Error(w, "invalid request", http.StatusBadRequest)
        return
    }

    output, err := h.registerUC.Execute(r.Context(), usecase.RegisterUserInput{
        Email:    req.Email,
        Password: req.Password,
    })
    if err != nil {
        // 实际应根据错误类型映射状态码
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(map[string]string{"user_id": output.UserID})
}

第五步:依赖注入与启动

在 main.go 中手动组装依赖(也可用 wire 等工具),这是整洁架构的关键——所有依赖在入口处注入,内层无需知道外层。


// cmd/api/main.go
package main

import (
    "database/sql"
    "log"
    "net/http"

    _ "github.com/go-sql-driver/mysql"
    "yourproject/internal/adapter/handler"
    "yourproject/internal/adapter/repository"
    "yourproject/internal/usecase"
)

func main() {
    db, err := sql.Open("mysql", "user:pass@tcp(localhost:3306)/test")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // 依赖注入:从外向内
    userRepo := repository.NewUserRepository(db)
    registerUC := usecase.NewRegisterUserUsecase(userRepo)
    userHandler := handler.NewUserHandler(registerUC)

    http.HandleFunc("/register", userHandler.Register)
    log.Println("server started on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

常见坑与解决方案

1. 事务管理如何不污染用例层?

事务是横切关注点。常见做法是在用例层使用 UnitOfWork 接口(定义在领域层),由适配器实现。例如:


type UnitOfWork interface {
    Do(ctx context.Context, fn func(context.Context) error) error
}

用例层通过 uow.Do 包裹操作,适配器用数据库事务实现。这样用例层不依赖 sql.Tx。

2. 错误映射

领域错误应定义为哨兵错误(如 ErrEmailExists),适配器层用 errors.Is 判断并映射为 HTTP 状态码。避免在用例层直接返回 http.StatusBadRequest。

3. 不要过度设计

Clean Architecture 适合中大型项目。如果项目很小,强行分层会增加复杂度。建议从简单分层开始,当业务变复杂时再逐步重构。

4. 循环依赖

严格遵循依赖方向:infrastructure → adapter → usecase → domain。如果发现内层 import 了外层,说明设计有问题,应提取接口到内层。

总结

Clean Architecture 的核心是依赖倒置和关注点分离。通过本文的实践,你掌握了:

  • 领域层定义实体和接口,用例层编排业务,适配器层处理技术细节
  • 依赖注入在入口处组装,内层不依赖外层
  • 事务、错误映射等横切问题的处理模式

下一步可以探索:使用 Wire 或 FX 自动化依赖注入、CQRS 模式、以及如何为用例层编写纯内存的单元测试。

> 本文代码示例可在 GitHub 仓库 clean-arch-demo 找到(虚构链接,实际请替换)。