包名採用**全小寫**、**反轉域名**作為前綴,確保全局唯一性,避免命名衝突。
// 標準格式
com.company.project.module.submodule
// 示例
com.alibaba.cloud.nacos.config
org.springframework.boot.autoconfigure
io.github.username.project.feature
com (商業)、org (非營利)、net、io、edu、gov 等。com.alibaba) 或 GitHub 用戶名 (io.github.username)。project 或 product。service, dao, controller, model, util, config 等。com.MyProject ❌mp.user.service ❌ (極高衝突風險)com.a.b.c.d.e.f.g ❌ (超過 5 層建議拆模塊)com.company.project.v2.service ❌ (應用模塊化管理版本)| 修飾符 | 同類 | 同包 | 子類(異包) | 非子類(異包) |
|---|---|---|---|---|
private | ✅ | ❌ | ❌ | ❌ |
default (package-private) | ✅ | ✅ | ❌ | ❌ |
protected | ✅ | ✅ | ✅ | ❌ |
public | ✅ | ✅ | ✅ | ✅ |
public 僅用於對外契約 (Controller, Service Interface, DTO, Event)。com.company.project
├── api // 公共契約:Interface, DTO, Event, Exception (public)
├── spi // 服務提供者接口:供第三方實現的擴展點
├── impl // 內部實現:ServiceImpl, RepositoryImpl (package-private 類)
│ ├── internal // 核心內部邏輯,嚴禁外部依賴
│ └── config // 自動配置類
└── infrastructure // 技術適配:MyBatis Mapper, Redis Client, MQ Producer
com.company.project
├── web // Controller, Filter, Interceptor (依賴 service)
├── service // Service Interface & Impl (依賴 dao, domain)
├── domain // Entity, VO, BO, Repository Interface (零依賴,核心層)
├── dao // Mapper, Repository Impl (依賴 domain, infrastructure)
└── infrastructure // DataSource, Redis, MQ, Feign Client 配置
project-api 和 project-impl,消費者僅依賴 api。com.example.mall
├── MallApplication.java
├── config // 全局配置類 (MyBatis, Redis, Security, Swagger)
├── common // 通用內核:Result, Constants, Enums, Exception, Util
├── module
│ ├── user
│ │ ├── api // UserService, UserDTO, UserVO, UserEvent
│ │ ├── impl // UserServiceImpl, UserRepositoryImpl
│ │ │ ├── converter // DTO/Entity/VO 轉換器
│ │ │ └── listener // 事件監聽器
│ │ └── infrastructure // UserMapper, UserPO, UserFeignClient
│ ├── order
│ │ ├── api
│ │ ├── impl
│ │ └── infrastructure
│ └── product
│ ├── api
│ ├── impl
│ └── infrastructure
└── infrastructure // 跨模塊基礎設施:DatabaseConfig, RedisConfig, MQConfig
包結構是項目架構的「骨架」。遵循**反轉域名命名**、**最小導出原則**、**依賴單向流動**、**業務模塊化拆分**,能構建清晰、可維護、可演進的 Java 系統。定期進行架構審查,清理循環依賴、收斂 public API,是技術治理的常態化工作。