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.

396 lines
12 KiB

2 months ago
2 months ago
2 months ago
2 months ago
2 months 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-dev.yml 文件,修改测试环境数据库连接配置:
  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. 编辑 src/main/resources/application-prod.yml 文件,修改生产环境数据库连接配置:
  66. ```
  67. spring:
  68. datasource:
  69. url: jdbc:mysql://localhost:3306/deepchart?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
  70. username: your_username # 修改为你的数据库用户名
  71. password: your_password # 修改为你的数据库密码
  72. ```
  73. ### 3. 启动应用
  74. #### 方式一:使用Maven
  75. ```
  76. mvn spring-boot:run
  77. ```
  78. #### 方式二:打包后运行
  79. ```
  80. mvn clean package
  81. java -jar target/springboot-demo-1.0.0.jar
  82. ```
  83. ### 4. 验证启动
  84. ```
  85. 访问 http://localhost:8080/api/actuator/health 查看应用健康状态。
  86. ```
  87. ## 核心功能
  88. ### 1. 统一响应格式
  89. 所有API返回统一的JSON格式:
  90. 成功响应:
  91. ```json
  92. {
  93. "code": 200,
  94. "message": "操作成功",
  95. "data": {
  96. "id": 1,
  97. "username": "testuser"
  98. },
  99. "timestamp": 1640995200000,
  100. "path": "/api/users/1"
  101. }
  102. ```
  103. 错误响应:
  104. ```json
  105. {
  106. "code": 400,
  107. "message": "参数错误: 用户名不能为空",
  108. "data": null,
  109. "timestamp": 1640995200000,
  110. "path": "/api/users"
  111. }
  112. ```
  113. ### 2. 全局异常处理
  114. 框架自动处理各类异常:
  115. |异常类型| HTTP状态码 |业务状态码| 处理说明|
  116. |-------|-------------|-----------|--------|
  117. |BusinessException| 200| 自定义| 业务逻辑异常|
  118. |MethodArgumentNotValidException| 200| 1001| 参数校验失败|
  119. |DataAccessException| 200| 1002| 数据访问异常|
  120. |其他异常| 200| 500| 系统内部错误|
  121. ### 3. 数据实体规范
  122. 所有实体类继承 BaseEntity,自动包含:
  123. * id: 主键
  124. * createTime: 创建时间
  125. * updateTime: 更新时间
  126. * deleted: 软删除标志
  127. * version: 乐观锁版本
  128. ### 4. 软删除支持
  129. 所有删除操作均为软删除,数据不会被物理删除:
  130. ```java
  131. // 软删除示例
  132. userRepository.softDelete(userId, LocalDateTime.now());
  133. ```
  134. ## 开发指南
  135. ### 1. 创建新实体
  136. ```java
  137. @Data
  138. @EqualsAndHashCode(callSuper = true)
  139. @Entity
  140. @Table(name = "product")
  141. public class Product extends BaseEntity {
  142. @NotBlank(message = "产品名称不能为空")
  143. @Column(nullable = false, length = 100)
  144. private String name;
  145. @Column(columnDefinition = "decimal(10,2)")
  146. private BigDecimal price;
  147. @Column(columnDefinition = "int default 1")
  148. private Integer status = 1;
  149. }
  150. ```
  151. ### 2. 创建Repository
  152. ```java
  153. @Repository
  154. public interface ProductRepository extends BaseRepository<Product> {
  155. // 派生查询方法
  156. List<Product> findByStatusOrderByCreateTimeDesc(Integer status);
  157. // 自定义查询
  158. @Query("SELECT p FROM Product p WHERE p.name LIKE %:keyword% AND p.deleted = false")
  159. Page<Product> searchProducts(@Param("keyword") String keyword, Pageable pageable);
  160. }
  161. ```
  162. ### 3. 创建Service
  163. ```java
  164. public interface ProductService extends BaseService<Product> {
  165. // 自定义业务方法
  166. Page<Product> searchProducts(String keyword, Pageable pageable);
  167. void changeProductStatus(Long id, Integer status);
  168. }
  169. @Service
  170. @Transactional
  171. @RequiredArgsConstructor
  172. public class ProductServiceImpl extends BaseServiceImpl<Product> implements ProductService {
  173. private final ProductRepository productRepository;
  174. @Override
  175. public Page<Product> searchProducts(String keyword, Pageable pageable) {
  176. return productRepository.searchProducts(keyword, pageable);
  177. }
  178. @Override
  179. public void changeProductStatus(Long id, Integer status) {
  180. Product product = getById(id);
  181. product.setStatus(status);
  182. productRepository.save(product);
  183. }
  184. }
  185. ```
  186. ### 4. 创建Controller
  187. ```java
  188. @RestController
  189. @RequestMapping("/products")
  190. @RequiredArgsConstructor
  191. public class ProductController extends BaseController<Product> {
  192. private final ProductService productService;
  193. public ProductController(ProductService productService) {
  194. super(productService);
  195. this.productService = productService;
  196. }
  197. @GetMapping("/search")
  198. public Result<Page<Product>> searchProducts(
  199. @RequestParam String keyword,
  200. @RequestParam(defaultValue = "0") int page,
  201. @RequestParam(defaultValue = "10") int size) {
  202. Pageable pageable = PageRequest.of(page, size);
  203. return Result.success(productService.searchProducts(keyword, pageable));
  204. }
  205. }
  206. ```
  207. ## 配置说明
  208. ### 数据库配置
  209. ``` yaml
  210. spring:
  211. datasource:
  212. hikari:
  213. maximum-pool-size: 20 # 最大连接数
  214. minimum-idle: 5 # 最小空闲连接
  215. connection-timeout: 30000 # 连接超时时间(ms)
  216. jpa:
  217. hibernate:
  218. ddl-auto: update # 表结构自动更新
  219. show-sql: true # 显示SQL
  220. properties:
  221. hibernate:
  222. format_sql: true # 格式化SQL
  223. dialect: org.hibernate.dialect.MySQL8Dialect
  224. ```
  225. 日志配置
  226. ```yaml
  227. logging:
  228. level:
  229. com.example.demo: DEBUG # 项目日志级别
  230. org.hibernate.SQL: DEBUG # Hibernate SQL日志
  231. org.hibernate.type: TRACE # SQL参数日志
  232. ```
  233. ## API示例
  234. ### 用户管理接口
  235. | 方法 | 路径 | 说明 |
  236. |------|--------------------|-----------|
  237. | POST | /api/users/create | 创建用户 |
  238. | POST | /api/users/update | 更新用户 |
  239. | GET | /api/users/detail | 获取用户详情 |
  240. | GET | /api/users/list | 用户列表(分页) |
  241. | GET | /api/users/delete | 删除用户 |
  242. | POST | /api/users/login | 用户登录 |
  243. | GET | /api/users/search | 搜索用户 |
  244. ## 使用示例
  245. ### 创建用户:
  246. ```bash
  247. curl -X POST http://localhost:8080/api/users/create \
  248. -H "Content-Type: application/json" \
  249. -d '{
  250. "username": "demo",
  251. "password": "123456",
  252. "email": "demo@example.com",
  253. "nickname": "演示用户"
  254. }'
  255. ```
  256. ### 查询用户列表:
  257. ```bash
  258. curl -X GET "http://localhost:8080/api/users/list?page=0&size=10&sort=createTime,desc"
  259. ```
  260. ### 用户登录:
  261. ```bash
  262. curl -X POST "http://localhost:8080/api/users/login?username=demo&password=123456"
  263. ```
  264. ## 测试指南
  265. ### 单元测试示例
  266. ```java
  267. @SpringBootTest
  268. class UserServiceTest {
  269. @Autowired
  270. private UserService userService;
  271. @Test
  272. void testCreateUser() {
  273. User user = new User();
  274. user.setUsername("testuser");
  275. user.setPassword("password");
  276. user.setEmail("test@example.com");
  277. User created = userService.createUser(user);
  278. assertNotNull(created.getId());
  279. assertEquals("testuser", created.getUsername());
  280. }
  281. }
  282. ```
  283. ### 集成测试示例
  284. ```java
  285. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  286. @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
  287. class UserControllerIntegrationTest {
  288. @LocalServerPort
  289. private int port;
  290. @Autowired
  291. private TestRestTemplate restTemplate;
  292. @Test
  293. @Order(1)
  294. void testCreateUser() {
  295. String url = "http://localhost:" + port + "/api/users";
  296. User user = new User();
  297. user.setUsername("integration_test");
  298. user.setPassword("password");
  299. user.setEmail("integration@test.com");
  300. ResponseEntity<Result> response = restTemplate.postForEntity(url, user, Result.class);
  301. assertEquals(HttpStatus.OK, response.getStatusCode());
  302. assertNotNull(response.getBody());
  303. assertEquals(200, response.getBody().getCode().intValue());
  304. }
  305. }
  306. ```
  307. ## 监控与调试
  308. ### 健康检查
  309. ```bash
  310. curl http://localhost:8080/api/actuator/health
  311. ```
  312. ### 应用信息
  313. ```bash
  314. curl http://localhost:8080/api/actuator/info
  315. ```
  316. ### 指标监控
  317. ```bash
  318. curl http://localhost:8080/api/actuator/metrics
  319. ```
  320. ## 常见问题
  321. ### 1. 数据库连接失败
  322. 问题:应用启动时报数据库连接错误
  323. 解决:检查 application.yml 中的数据库配置,确保数据库服务已启动。
  324. ### 2. 表结构不自动更新
  325. 问题:实体类修改后表结构未更新
  326. 解决:检查 ddl-auto 配置,开发环境建议使用 update。
  327. ### 3. 查询性能问题
  328. 问题:复杂查询性能较差
  329. 解决:使用 @Query 注解编写优化SQL,或使用数据库索引。
  330. ### 4. 事务不生效
  331. 问题:Service方法中的事务未正确回滚
  332. 解决:确保Service方法添加 @Transactional 注解,且异常为RuntimeException。
  333. ## 开发规范
  334. ### 代码规范
  335. * 命名规范:使用驼峰命名法,类名首字母大写
  336. * 注释要求:公共方法必须添加注释,复杂逻辑添加行内注释
  337. * 异常处理:使用框架提供的统一异常处理,不捕获异常后静默处理
  338. ### API设计规范
  339. * RESTful风格:使用HTTP方法表示操作类型
  340. * 统一响应:所有接口返回统一的Result格式
  341. * 错误码规范:使用预定义的错误码,不随意创建新错误码
  342. ### 数据库规范
  343. * 软删除:所有删除操作使用软删除
  344. * 索引优化:频繁查询的字段添加索引
  345. * 字段长度:字符串字段根据业务需求设置合适长度