后端開發: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 設計指南