2026年开年王炸项目"全球最懂机构行为的AI"
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

388 lines
12 KiB

1 month ago
  1. # 这是一个基于 Spring Boot 3.2.5 + Java 17 + MySQL 8.0 构建的现代化企业级开发框架,采用经典的 Repository + Service 分层架构,提供了完整的项目基础结构和最佳实践。
  2. ## 设计理念
  3. - **开箱即用**:提供完整的基础架构,快速启动新项目
  4. - **规范统一**:统一的代码风格、异常处理、返回格式
  5. - **易于扩展**:模块化设计,便于功能扩展和维护
  6. - **生产就绪**:包含监控、日志、事务等生产环境必需功能
  7. ## 技术栈
  8. | 技术领域 | 技术选型 |
  9. |--------------|----------------------------------|
  10. | 后端框架 | Spring Boot 3.2.5 |
  11. | Java版本 | Java 17 |
  12. | 数据库 | MySQL 8.0 |
  13. | ORM框架 | Spring Data JPA + Hibernate |
  14. | 依赖管理 | Maven |
  15. | 日志框架 | SLF4J + Logback |
  16. | 监控 | Spring Boot Actuator |
  17. ## 项目结构
  18. ```text
  19. src/main/java/com/deepchart
  20. ├── DemoApplication.java # 应用启动类(程序入口)
  21. ├── config/ # 配置类目录
  22. │ ├── JpaConfig.java # JPA配置(实体映射、查询优化等)
  23. │ └── WebConfig.java # Web MVC配置(拦截器、资源映射等)
  24. ├── common/ # 通用组件(全局复用)
  25. │ ├── result/ # 统一返回结果封装
  26. │ │ ├── Result.java # 统一响应体(含code、message、data等)
  27. │ │ └── ResultCode.java # 状态码枚举(成功/失败/参数错误等)
  28. │ └── exception/ # 异常处理
  29. │ ├── GlobalExceptionHandler.java # 全局异常拦截器(统一处理所有异常)
  30. │ └── BusinessException.java # 业务异常类(自定义业务错误)
  31. ├── entity/ # 数据库实体类(与表结构映射)
  32. │ ├── BaseEntity.java # 基础实体类(含公共字段:id、时间戳等)
  33. │ └── User.java # 用户实体类(示例)
  34. ├── repository/ # 数据访问层(操作数据库)
  35. │ ├── BaseRepository.java # 基础Repository(封装通用CRUD)
  36. │ └── UserRepository.java # 用户Repository(用户表专属操作)
  37. ├── service/ # 业务逻辑层(核心业务处理)
  38. │ ├── UserService.java # 用户服务接口(定义业务方法)
  39. │ └── impl/ # 服务实现类
  40. │ └── UserServiceImpl.java # 用户服务实现(接口方法具体逻辑)
  41. └── controller/ # 控制层(接收请求、返回响应)
  42. └── UserController.java # 用户控制器(处理用户相关API)
  43. ```
  44. ## 快速开始
  45. ### 环境要求
  46. - JDK 17 或更高版本
  47. - Maven 3.6 或更高版本
  48. - MySQL 8.0 或更高版本
  49. ### 1. 数据库准备
  50. ```sql
  51. -- 创建数据库
  52. CREATE DATABASE IF NOT EXISTS deepchart CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
  53. -- 使用数据库
  54. USE demo_db;
  55. ```
  56. ### 2. 配置修改
  57. 编辑 src/main/resources/application.properties 文件,修改数据库连接配置:
  58. ```
  59. spring:
  60. datasource:
  61. url: jdbc:mysql://localhost:3306/deepchart?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
  62. username: your_username # 修改为你的数据库用户名
  63. password: your_password # 修改为你的数据库密码
  64. ```
  65. ### 3. 启动应用
  66. #### 方式一:使用Maven
  67. ```
  68. mvn spring-boot:run
  69. ```
  70. #### 方式二:打包后运行
  71. ```
  72. mvn clean package
  73. java -jar target/springboot-demo-1.0.0.jar
  74. ```
  75. ### 4. 验证启动
  76. ```
  77. 访问 http://localhost:8080/api/actuator/health 查看应用健康状态。
  78. ```
  79. ## 核心功能
  80. ### 1. 统一响应格式
  81. 所有API返回统一的JSON格式:
  82. 成功响应:
  83. ```json
  84. {
  85. "code": 200,
  86. "message": "操作成功",
  87. "data": {
  88. "id": 1,
  89. "username": "testuser"
  90. },
  91. "timestamp": 1640995200000,
  92. "path": "/api/users/1"
  93. }
  94. ```
  95. 错误响应:
  96. ```json
  97. {
  98. "code": 400,
  99. "message": "参数错误: 用户名不能为空",
  100. "data": null,
  101. "timestamp": 1640995200000,
  102. "path": "/api/users"
  103. }
  104. ```
  105. ### 2. 全局异常处理
  106. 框架自动处理各类异常:
  107. |异常类型| HTTP状态码 |业务状态码| 处理说明|
  108. |-------|-------------|-----------|--------|
  109. |BusinessException| 200| 自定义| 业务逻辑异常|
  110. |MethodArgumentNotValidException| 200| 1001| 参数校验失败|
  111. |DataAccessException| 200| 1002| 数据访问异常|
  112. |其他异常| 200| 500| 系统内部错误|
  113. ### 3. 数据实体规范
  114. 所有实体类继承 BaseEntity,自动包含:
  115. * id: 主键
  116. * createTime: 创建时间
  117. * updateTime: 更新时间
  118. * deleted: 软删除标志
  119. * version: 乐观锁版本
  120. ### 4. 软删除支持
  121. 所有删除操作均为软删除,数据不会被物理删除:
  122. ```java
  123. // 软删除示例
  124. userRepository.softDelete(userId, LocalDateTime.now());
  125. ```
  126. ## 开发指南
  127. ### 1. 创建新实体
  128. ```java
  129. @Data
  130. @EqualsAndHashCode(callSuper = true)
  131. @Entity
  132. @Table(name = "product")
  133. public class Product extends BaseEntity {
  134. @NotBlank(message = "产品名称不能为空")
  135. @Column(nullable = false, length = 100)
  136. private String name;
  137. @Column(columnDefinition = "decimal(10,2)")
  138. private BigDecimal price;
  139. @Column(columnDefinition = "int default 1")
  140. private Integer status = 1;
  141. }
  142. ```
  143. ### 2. 创建Repository
  144. ```java
  145. @Repository
  146. public interface ProductRepository extends BaseRepository<Product> {
  147. // 派生查询方法
  148. List<Product> findByStatusOrderByCreateTimeDesc(Integer status);
  149. // 自定义查询
  150. @Query("SELECT p FROM Product p WHERE p.name LIKE %:keyword% AND p.deleted = false")
  151. Page<Product> searchProducts(@Param("keyword") String keyword, Pageable pageable);
  152. }
  153. ```
  154. ### 3. 创建Service
  155. ```java
  156. public interface ProductService extends BaseService<Product> {
  157. // 自定义业务方法
  158. Page<Product> searchProducts(String keyword, Pageable pageable);
  159. void changeProductStatus(Long id, Integer status);
  160. }
  161. @Service
  162. @Transactional
  163. @RequiredArgsConstructor
  164. public class ProductServiceImpl extends BaseServiceImpl<Product> implements ProductService {
  165. private final ProductRepository productRepository;
  166. @Override
  167. public Page<Product> searchProducts(String keyword, Pageable pageable) {
  168. return productRepository.searchProducts(keyword, pageable);
  169. }
  170. @Override
  171. public void changeProductStatus(Long id, Integer status) {
  172. Product product = getById(id);
  173. product.setStatus(status);
  174. productRepository.save(product);
  175. }
  176. }
  177. ```
  178. ### 4. 创建Controller
  179. ```java
  180. @RestController
  181. @RequestMapping("/products")
  182. @RequiredArgsConstructor
  183. public class ProductController extends BaseController<Product> {
  184. private final ProductService productService;
  185. public ProductController(ProductService productService) {
  186. super(productService);
  187. this.productService = productService;
  188. }
  189. @GetMapping("/search")
  190. public Result<Page<Product>> searchProducts(
  191. @RequestParam String keyword,
  192. @RequestParam(defaultValue = "0") int page,
  193. @RequestParam(defaultValue = "10") int size) {
  194. Pageable pageable = PageRequest.of(page, size);
  195. return Result.success(productService.searchProducts(keyword, pageable));
  196. }
  197. }
  198. ```
  199. ## 配置说明
  200. ### 数据库配置
  201. ``` yaml
  202. spring:
  203. datasource:
  204. hikari:
  205. maximum-pool-size: 20 # 最大连接数
  206. minimum-idle: 5 # 最小空闲连接
  207. connection-timeout: 30000 # 连接超时时间(ms)
  208. jpa:
  209. hibernate:
  210. ddl-auto: update # 表结构自动更新
  211. show-sql: true # 显示SQL
  212. properties:
  213. hibernate:
  214. format_sql: true # 格式化SQL
  215. dialect: org.hibernate.dialect.MySQL8Dialect
  216. ```
  217. 日志配置
  218. ```yaml
  219. logging:
  220. level:
  221. com.example.demo: DEBUG # 项目日志级别
  222. org.hibernate.SQL: DEBUG # Hibernate SQL日志
  223. org.hibernate.type: TRACE # SQL参数日志
  224. ```
  225. ## API示例
  226. ### 用户管理接口
  227. |方法| 路径 | 说明 |
  228. |----|-------------------------|-----------|
  229. |POST| /api/users| 创建用户 |
  230. |PUT| /api/users/{id}| 更新用户 |
  231. |GET| /api/users/{id}| 获取用户详情 |
  232. |GET| /api/users| 用户列表(分页) |
  233. |DELETE| /api/users/{id}| 删除用户 |
  234. |POST| /api/users/login| 用户登录 |
  235. |GET| /api/users/search| 搜索用户 |
  236. ## 使用示例
  237. ### 创建用户:
  238. ```bash
  239. curl -X POST http://localhost:8080/api/users \
  240. -H "Content-Type: application/json" \
  241. -d '{
  242. "username": "demo",
  243. "password": "123456",
  244. "email": "demo@example.com",
  245. "nickname": "演示用户"
  246. }'
  247. ```
  248. ### 查询用户列表:
  249. ```bash
  250. curl -X GET "http://localhost:8080/api/users?page=0&size=10&sort=createTime,desc"
  251. ```
  252. ### 用户登录:
  253. ```bash
  254. curl -X POST "http://localhost:8080/api/users/login?username=demo&password=123456"
  255. ```
  256. ## 测试指南
  257. ### 单元测试示例
  258. ```java
  259. @SpringBootTest
  260. class UserServiceTest {
  261. @Autowired
  262. private UserService userService;
  263. @Test
  264. void testCreateUser() {
  265. User user = new User();
  266. user.setUsername("testuser");
  267. user.setPassword("password");
  268. user.setEmail("test@example.com");
  269. User created = userService.createUser(user);
  270. assertNotNull(created.getId());
  271. assertEquals("testuser", created.getUsername());
  272. }
  273. }
  274. ```
  275. ### 集成测试示例
  276. ```java
  277. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  278. @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
  279. class UserControllerIntegrationTest {
  280. @LocalServerPort
  281. private int port;
  282. @Autowired
  283. private TestRestTemplate restTemplate;
  284. @Test
  285. @Order(1)
  286. void testCreateUser() {
  287. String url = "http://localhost:" + port + "/api/users";
  288. User user = new User();
  289. user.setUsername("integration_test");
  290. user.setPassword("password");
  291. user.setEmail("integration@test.com");
  292. ResponseEntity<Result> response = restTemplate.postForEntity(url, user, Result.class);
  293. assertEquals(HttpStatus.OK, response.getStatusCode());
  294. assertNotNull(response.getBody());
  295. assertEquals(200, response.getBody().getCode().intValue());
  296. }
  297. }
  298. ```
  299. ## 监控与调试
  300. ### 健康检查
  301. ```bash
  302. curl http://localhost:8080/api/actuator/health
  303. ```
  304. ### 应用信息
  305. ```bash
  306. curl http://localhost:8080/api/actuator/info
  307. ```
  308. ### 指标监控
  309. ```bash
  310. curl http://localhost:8080/api/actuator/metrics
  311. ```
  312. ## 常见问题
  313. ### 1. 数据库连接失败
  314. 问题:应用启动时报数据库连接错误
  315. 解决:检查 application.yml 中的数据库配置,确保数据库服务已启动。
  316. ### 2. 表结构不自动更新
  317. 问题:实体类修改后表结构未更新
  318. 解决:检查 ddl-auto 配置,开发环境建议使用 update。
  319. ### 3. 查询性能问题
  320. 问题:复杂查询性能较差
  321. 解决:使用 @Query 注解编写优化SQL,或使用数据库索引。
  322. ### 4. 事务不生效
  323. 问题:Service方法中的事务未正确回滚
  324. 解决:确保Service方法添加 @Transactional 注解,且异常为RuntimeException。
  325. ## 开发规范
  326. ### 代码规范
  327. * 命名规范:使用驼峰命名法,类名首字母大写
  328. * 注释要求:公共方法必须添加注释,复杂逻辑添加行内注释
  329. * 异常处理:使用框架提供的统一异常处理,不捕获异常后静默处理
  330. ### API设计规范
  331. * RESTful风格:使用HTTP方法表示操作类型
  332. * 统一响应:所有接口返回统一的Result格式
  333. * 错误码规范:使用预定义的错误码,不随意创建新错误码
  334. ### 数据库规范
  335. * 软删除:所有删除操作使用软删除
  336. * 索引优化:频繁查询的字段添加索引
  337. * 字段长度:字符串字段根据业务需求设置合适长度