后端开发:Spring Boot 快速开发实战
引言
在现代后端开发中,Spring Boot 因其轻量级、快速开发的特性而备受开发者青睐。本文将带你从零开始,使用 Spring Boot + MyBatis 实现一个完整的 RESTful API,并深入探讨如何优雅地处理异常和日志记录。无论你是初学者还是有一定经验的开发者,这篇笔记都能为你提供实用的知识点。
一、环境准备
1. 安装依赖工具
确保你已经安装了以下工具:
- JDK 8 或更高版本
- Maven(构建工具)
- IDE(如 IntelliJ IDEA 或 VS Code)
2. 创建 Spring Boot 项目
使用 Spring Initializr 快速生成项目骨架:
- 访问 Spring Initializr 网站。
- 配置项目信息:
- Project: Maven Project
- Language: Java
- Spring Boot: 最新稳定版本
- Dependencies: 添加
Spring Web
,MyBatis Framework
,MySQL Driver
- 下载并解压项目,导入到 IDE 中。
二、Spring Boot + MyBatis 实现 RESTful API 的完整流程
1. 数据库设计
假设我们要开发一个简单的用户管理系统,包含以下字段:
id
(主键)name
(用户名)email
(邮箱)
SQL 脚本
CREATE DATABASE user_management;USE user_management;CREATE TABLE users (id BIGINT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(100) NOT NULL,email VARCHAR(100) NOT NULL UNIQUE
);
2. 配置数据库连接
在 application.properties
文件中配置 MySQL 数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/user_management?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml
3. 创建实体类
创建一个 User
实体类,与数据库表对应:
package com.example.demo.entity;public class User {private Long id;private String name;private String email;// Getters and Setters
}
4. 创建 Mapper 接口
使用 MyBatis 的注解或 XML 配置方式定义数据访问层接口:
package com.example.demo.mapper;import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;import java.util.List;@Mapper
public interface UserMapper {@Select("SELECT * FROM users")List<User> findAll();@Select("SELECT * FROM users WHERE id = #{id}")User findById(Long id);@Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")@Options(useGeneratedKeys = true, keyProperty = "id")void insert(User user);@Update("UPDATE users SET name=#{name}, email=#{email} WHERE id=#{id}")void update(User user);@Delete("DELETE FROM users WHERE id=#{id}")void delete(Long id);
}
5. 创建 Service 层
封装业务逻辑,调用 Mapper 接口:
package com.example.demo.service;import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public List<User> getAllUsers() {return userMapper.findAll();}public User getUserById(Long id) {return userMapper.findById(id);}public void createUser(User user) {userMapper.insert(user);}public void updateUser(User user) {userMapper.update(user);}public void deleteUser(Long id) {userMapper.delete(id);}
}
6. 创建 Controller 层
暴露 RESTful API 接口:
package com.example.demo.controller;import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/api/users")
public class UserController {@Autowiredprivate UserService userService;@GetMappingpublic List<User> getAllUsers() {return userService.getAllUsers();}@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userService.getUserById(id);}@PostMappingpublic void createUser(@RequestBody User user) {userService.createUser(user);}@PutMapping("/{id}")public void updateUser(@PathVariable Long id, @RequestBody User user) {user.setId(id);userService.updateUser(user);}@DeleteMapping("/{id}")public void deleteUser(@PathVariable Long id) {userService.deleteUser(id);}
}
三、如何优雅地处理异常和日志记录?
1. 全局异常处理
使用 @ControllerAdvice
注解实现全局异常处理,避免重复代码:
package com.example.demo.exception;import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public ResponseEntity<String> handleException(Exception ex) {return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);}@ExceptionHandler(ResourceNotFoundException.class)public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);}
}
自定义异常类:
package com.example.demo.exception;public class ResourceNotFoundException extends RuntimeException {public ResourceNotFoundException(String message) {super(message);}
}
2. 日志记录
使用 SLF4J
和 Logback
记录日志,便于调试和问题追踪:
package com.example.demo.controller;import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/api/users")
public class UserController {private static final Logger logger = LoggerFactory.getLogger(UserController.class);@Autowiredprivate UserService userService;@GetMappingpublic List<User> getAllUsers() {logger.info("Fetching all users");return userService.getAllUsers();}@PostMappingpublic void createUser(@RequestBody User user) {logger.info("Creating user: {}", user);userService.createUser(user);}
}
四、总结
通过本文,我们完成了以下内容:
- 使用 Spring Boot 和 MyBatis 实现了一个完整的 RESTful API。
- 学习了如何优雅地处理异常和记录日志。
这些技能是后端开发的核心能力,能够帮助你在实际项目中快速构建高效、稳定的系统。希望这篇文章能为你提供实用的指导,并助力你在以后的只有我道路上有目标,向钱进!
参考链接
- Spring Boot 官方文档
- MyBatis 官方文档
- RESTful API 设计指南