1. 架构选型与决策矩阵

1.1 依赖注入模式决策矩阵

注入模式声明形式不可变性保障纯单元测试友好度循环依赖风险架构推荐级别
构造器注入 (Constructor)private final Dep dep; public Service(Dep dep) {...}完全不可变 (final)极佳(直接 new 传入 Mock 对象)启动期即刻显式暴露并失败生产唯一推荐首选
Setter 注入@Autowired public void setDep(Dep dep) {...}允许运行时二次篡改需调用 setter 手动设值运行时可能掩盖架构设计异味仅在极少数可选依赖使用
字段注入 (Field)@Autowired private Dep dep;破坏封装与不可变性恶劣(强依赖反射或 Spring 容器)难以追踪与防御循环依赖严禁在生产代码中使用

1.2 RESTful API 版本化策略决策矩阵

版本策略实现范例URL 纯净度网关与 CDN 缓存友好度客户端调试成本生产适用场景
URI 路径版本化/api/v1/books含有版本前缀极高(天然作为缓存 Key)极低(浏览器与 cURL 直接可测)企业公网与前后端分离系统首选
Header 请求头版本化X-API-VERSION: 2保持纯净中等(需配置 Vary 头协同缓存)较高(需构造自定义 Header)内部微服务调用或协议严格稳定的系统
MIME 内容协商版本化Accept: application/vnd.bookstore.v2+json保持纯净较低(多维度 Vary 规则较重)高(需要精确请求 Accept 报文)成熟超媒体 RESTful 规范(HATEOAS)

2. 生产级高内聚服务与 API 代码范式

2.1 不可变 Record DTO 与 Bean Validation 校验契约

java
package com.packt.bookstore.inventory.dto;
 
import jakarta.validation.constraints.*;
import java.math.BigDecimal;
import java.time.LocalDate;
 
public record BookRequest(
        @NotBlank(message = "Title is required and cannot be blank")
        String title,
 
        @NotBlank(message = "ISBN is required")
        @Pattern(regexp = "^[0-9-]{10,17}$", message = "ISBN must be 10-17 digits and may include dashes")
        String isbn,
 
        @NotNull(message = "Author ID is required")
        Long authorId,
 
        @NotNull(message = "Price is required")
        @PositiveOrZero(message = "Price must be greater than or equal to 0")
        BigDecimal price,
 
        @PositiveOrZero(message = "Quantity must be >= 0")
        Integer quantity,
 
        String genre,
        LocalDate published,
        String description,
        Integer pageCount,
        String coverImageUrl
) {}

2.2 生产级业务服务层(BookService 核心逻辑与语义校验)

java
package com.packt.bookstore.inventory.service.impl;
 
import com.packt.bookstore.inventory.dto.*;
import com.packt.bookstore.inventory.entity.*;
import com.packt.bookstore.inventory.exception.*;
import com.packt.bookstore.inventory.mapper.BookMapper;
import com.packt.bookstore.inventory.repository.*;
import com.packt.bookstore.inventory.service.IBookService;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.util.List;
 
@Service
public class BookService implements IBookService {
 
    private final BookRepository bookRepository;
    private final AuthorRepository authorRepository;
    private final BookMapper bookMapper;
 
    public BookService(BookRepository bookRepository, 
                       AuthorRepository authorRepository, 
                       BookMapper bookMapper) {
        this.bookRepository = bookRepository;
        this.authorRepository = authorRepository;
        this.bookMapper = bookMapper;
    }
 
    @Override
    @Transactional(readOnly = true)
    public List<BookResponse> findAll(int page, int size, String sortSpec) {
        PageRequest pageRequest = PageRequest.of(page, size, Sort.by("title").ascending());
        return bookRepository.findAll(pageRequest).getContent().stream()
                .map(bookMapper::toResponse)
                .toList();
    }
 
    @Override
    @Transactional(readOnly = true)
    public BookResponse findOne(Long id) {
        Book book = bookRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Book with ID " + id + " not found"));
        return bookMapper.toResponse(book);
    }
 
    @Override
    @Transactional
    public BookResponse create(BookRequest req) {
        if (req.authorId() == null) {
            throw new DomainRuleViolationException("Author ID is required");
        }
        if (req.price() != null && req.price().compareTo(BigDecimal.ZERO) < 0) {
            throw new DomainRuleViolationException("Price cannot be negative");
        }
        if (req.isbn() != null && bookRepository.existsByIsbnIgnoreCase(req.isbn())) {
            throw new DomainRuleViolationException("ISBN must be unique within the catalog");
        }
        Author author = authorRepository.findById(req.authorId())
                .orElseThrow(() -> new ResourceNotFoundException("Author with ID " + req.authorId() + " not found"));
        Book saved = bookRepository.save(bookMapper.toEntity(req, author));
        return bookMapper.toResponse(saved);
    }
 
    @Override
    @Transactional
    public void delete(Long id) {
        if (!bookRepository.existsById(id)) {
            throw new ResourceNotFoundException("Book with ID " + id + " not found");
        }
        bookRepository.deleteById(id);
    }
}

2.3 RFC 9457 统一错误信封与全局异常切面

java
package com.packt.bookstore.inventory.dto;
 
import java.time.Instant;
 
public record ApiError(
        String type,
        String title,
        int status,
        String detail,
        String instance,
        Instant timestamp
) {
    private static final String BASE_TYPE_URL = "https://api.bookstore.com/errors/";
 
    public static ApiError of(String errorKey, String title, int status, String detail, String instance) {
        return new ApiError(BASE_TYPE_URL + errorKey, title, status, detail, instance, Instant.now());
    }
}
java
package com.packt.bookstore.inventory.exception;
 
import com.packt.bookstore.inventory.dto.ApiError;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
@RestControllerAdvice
public class GlobalExceptionHandler {
 
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ApiError> handleNotFound(ResourceNotFoundException ex, HttpServletRequest req) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(ApiError.of("not-found", "Not Found", 404, ex.getMessage(), req.getRequestURI()));
    }
 
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiError> handleValidation(MethodArgumentNotValidException ex, HttpServletRequest req) {
        String detail = ex.getBindingResult().getFieldErrors().stream()
                .map(fe -> fe.getField() + ": " + fe.getDefaultMessage())
                .findFirst().orElse("Validation failed");
        return ResponseEntity.badRequest()
                .body(ApiError.of("bad-request", "Bad Request", 400, detail, req.getRequestURI()));
    }
 
    @ExceptionHandler(DomainRuleViolationException.class)
    public ResponseEntity<ApiError> handleDomainRule(DomainRuleViolationException ex, HttpServletRequest req) {
        return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY)
                .body(ApiError.of("unprocessable-entity", "Domain Rule Violation", 422, ex.getMessage(), req.getRequestURI()));
    }
 
    @ExceptionHandler(DataIntegrityViolationException.class)
    public ResponseEntity<ApiError> handleConflict(DataIntegrityViolationException ex, HttpServletRequest req) {
        return ResponseEntity.status(HttpStatus.CONFLICT)
                .body(ApiError.of("conflict", "Data Conflict", 409, "A data conflict occurred in database", req.getRequestURI()));
    }
}

3. 全局参数校验与异常状态码映射拓扑流图

text
[ 客户端 HTTP 请求 ]
       │
       ▼
[ Web 控制器层: @Valid 参数结构校验 ] ──(格式校验失败)──> [ 400 Bad Request ]
       │ (结构合法)
       ▼
[ 服务层: validateSemantics 业务语义校验 ] ──(语义冲突)──> [ 422 Unprocessable Entity ]
       │ (业务合法)
       ▼
[ 仓储与实体检索: findById ] ──────────(主键未命中)───> [ 404 Not Found ]
       │ (找到实体)
       ▼
[ 持久化写入: save ] ──────────────────(唯一索引冲突)─> [ 409 Conflict ]
       │ (持久化成功)
       ▼
[ 成功响应: 200 OK / 201 Created (Location Header) / 204 No Content ]

4. API 与服务层避坑清单 (Do's & Don'ts)

错误实践 (Don't)正确实践 (Do)
在 Controller 中混杂业务规则计算、直接操作 Repository 或开启事务。保持 Thin Controller 设计,所有业务与事务一律封装在 IBookService 服务契约中。
在生产代码中盲目依赖 @Autowired 字段注入。强制采用构造器注入(Constructor Injection),声明 private final 字段。
直接把内部 @Entity 持久化对象序列化返回给外部客户端。使用 Java record 作为不可变 DTO,通过独立 Mapper 隔绝持久化细节与外部契约。
全量 API 一律返回 200 OK,并在 JSON 内部自造 { code: 500, msg: "..." }。严格遵从 HTTP 动词与 RFC 9457 标准状态码(200/201/204/400/404/422/500)。
在每个 Controller 方法中层层包裹 try/catch 吞没异常。使用 @RestControllerAdvice 集中捕获特定异常并统一映射为标准化错误信封。